Haskell 语言入门
h (x, y) = f( x) + g( x, y)
在Haskell中对应的也就是:h x y = f x + g x
函数名和 参数之间用空格分隔
// 调用函数 hello不加(), print是一个库函数
main = print hello
// 最简单的函数hello 没有参数,= 右侧放的就是函数体,函数一定要有返回值 hello =12
// 进阶一下,函数变成两个参数
main = print (plus 2 8)
plus a b = a+b
// 复杂一点
main = print (get(-1)) get x = if x>0 then x else -x
// 小心换行不能用Tab
//特有的一些用法
// 看这个例子
main = print (fib 6) fib 0=0 fib 1=1 fib x = if x<0 then -1 else fib(x-1)+fib(x-2)
// 改造一下
fib 0=0 fib 1=1 fib x | x<0 = -1 | otherwise =fib(x-1)+fib(x-2)
// 定义局部变量
health weight height | bmi <= skinny = "You're underweight!" | bmi <= normal = "You're supposedly normal!" | bmi <= fat = "You're fat! " | otherwise = "You're a whale!" where bmi = weight / height ^ 2 skinny = 18.5 normal = 25.0 fat = 30.0
main = test test = do let f x y = x+y print (f 2 3)
// 注意上面的where 就是定义局部变量
// 多条语句需要加一个do 这样才能写一个语句块
main = hello hello= do print "123456" print "aaaa"
print "bbbb"
print "cccc"
print "dddd"
// 当参数是一个函数时
main = do print (callf test1 10) print (callf test2 10) print (callf test3 "dd") callf f x = f x test1 x = x*2 test2 x = x+2 test3 x= x++x
// 改成用Lambda
main = do print (callf (\x->x*2) 10) print (callf (\x->x+2) 10) print (callf (\x->x++x) "dd") callf f x = f x