[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 JavaTuples
- 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