Scala 笔记1

[update 2018/09/16]

Scala

打算学习Scala, 虽然语法远远不如Haskell简洁, 但是人家库多。->_<-

0. Scala For Haskellers

1. STD LIB

  • assert
expr :: Boolean
assert(expr)
  • classes

    Classes in Scala are static templates that can be instantiated into many objects at runtime

  • Option (Maybe)

Option[TypeA] = Some(TypeA) | None
  • Objects

    An object is a singleton.
    One object, that’s it.
    This object is a replacement of static in Java

  • Tuples

    • Fixed number of items with different types
    • immutable
val tuple = ("apple", "dog")
val fruit = tuple._1 // "apple"
val animal = tuple._2 // "dog"
  • Higher Order Functions

function definitions

def lambda = { x: Int ⇒
  x + 1
}
def lambda2 = (x: Int) ⇒ x + 2
val lambda3 = (x: Int) ⇒ x + 3

val lambda4 = new Function1[Int, Int] {
  def apply(v1: Int): Int = v1 - 1
}

def lambda5(x: Int) = x + 1

val result = lambda(3)
val `result1andhalf` = lambda.apply(3)

Another example for haskell

result=fromtoexpr(x) r e s u l t = ∑ f r o m t o e x p r ( x )

result=x=1100001x2 r e s u l t = ∑ x = 1 10000 1 x 2

-- haskell
cal :: Int -> Int -> (Int -> Int) -> (Int -> Double) -> Double -> Double
cal from to next expr result 
    | from > to = result
    | otherwise = cal (next from) to next expr (result + expr from)
object fromTo extends App {
    def cal(from: Int, to: Int, next: Int => Int, expr: Int => Double, result: Double): Double = {
        if (from > to) result
        else cal(next(from), to, next, expr, result + expr(from))
    }

    def next(x: Int) = {x + 2}
    def expr(x: Int) = {1.0 / (x * x)}
    val result = cal(1, 100000, next, expr, 0);
    println(result); // 1.2336846796247811
}


  • Lists

Scala Lists are quite similar to arrays, which means all the elements of a list have the same type, but there are two important differences.
- First, lists are immutable, which means elements of a list cannot be changed by assignment.
- Second, lists represent a linked list whereas arrays are flat.

The type of a list that has elements of type T is written as List[T].
// eq tests identity (same object):
val a = List(1, 2, 3)
val b = List(1, 2, 3)

a eq b == false
a == b == true

// Nil lists are identical
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值