Functional Programming
经常听人提及函数式编程,“函数式编程只做一件事,定义”,“函数式编程将会是下一个主流的编程模式”。。
于是找了个介绍的MOOC,由于用的是Haskell,所以顺便学下。。。
[课程名:EDX FP101X]
(https://courses.edx.org/courses/DelftX/FP101x/3T2014/info)
学习资料:
Haskell运行环境
课程推荐GHCi(类似一个解释器),Windows下直接安装
GHCi基本命令
:load name load script name
:reload reload current script
:edit name edit script name
:edit edit current script
:type expr show type of expr
:? show all commands
:quit quit GHCi
Haskell基本语法
Haskell 对齐规则和python类似
以空格表示应用函数
即 f (x,y)表示为 f x y
还可以用中缀表示, x `f` y
f(x,g(x,y)) => f x (g x y)
列表
Haskell的列表不是随机访问的
head [1, 2, 3]
tail [1, 2, 3]
take 2 [1, 2, 3]
drop 2 [1, 2, 3]
示例数学函数
double x = x + x
quadruble x = double (double x)
factorial n = product [1..n]
average ns = sum ns `div` length ns
类型
Bool - logical values
Char - single characters
String - strings of characters
Int - fixed-precision integers
Integer - arbitrary-precision integers
Float - floating-point numbers
tuple - 元组
声明类型
->是右结合的,x->y->z 等价于 x->(y->z)
而在应用函数的时候,空格是左结合的
f x y z 等价 f (x y) z
add :: Int -> (Int->Int)
add x y = x+y
Curried Functions
克里化函数,如上面的add,先接受x作为参数,返回,add x,然后接受y作为参数,返回 x+y
这种函数每次只接受一个参数