最近开始接触Ocaml,一开始也是摸不着头脑。看着PPT,学习一下。
Ocaml 有几个比较显著的特征
1.Value 为中心
所有的一切都是value
一旦定义了就无法改变了
2.函数型的语言
函数也是value
3.具有严格的类型type
保障程序的安全
ML的有很多,比较有名的有Ocaml(INRIA,France) SML(Bell,lab&Princeton USA) 顺便提一下我们教授开发的nML(SNU/KAIST)
1.Let
给Value一个名字
(* ex1.ml *)
let a = 10
let add x y =
x + y
let sumofsquare x y =
let sqx = x * x in
let sqy = y * y in
sqx + sqy
(* ex2.ml *)
let sumofsquare x y =
let square x = x * x in
square x + square y
2.If,match
判断语句
(* ex3.ml *)
let isEven n =
if n mod 2 = 0 then true
else false
if 语句必须有完整的格式 if…then…else 因为 必须保证 n有一个value
(* ex4.ml *)
let isEven n =
match n mod 2 with
0 -> true
| 1 -> false
和ex3.ml有相同的效果,只是换了一种形式 match…with 有点像switch
(* ex5.ml *)
let is3mulitple n =
match n mod 3 with
0 -> true
| _ –> false
_->false 表示除了0 以外的任意 integer 都是false
3.Function
-3.1一般的函数
let isEven n =
if n mod 2 = 0 then true
else false
函数也是value,理解这点很重要
-3.2 没有名字的函数
(fun x –>10+ x)
-3.3 递归函数
let rec fac n =
if n = 0 then 1
else n * fac(n-1)
递归函数的定义要有一个 rec
4.类型 Type
Ocaml 可以自动判断value的类型,这一点是很牛的,能够避免很多因为类型声明造成的错误
Ocaml自身也带有很多基本类型,int,string,list,tuple,record等
自己可以定义类型
5.比较严格的类型区分
5.1
2+2.5 是错误的表达式 int 和float 不能相加
=>(float_of_int 2) +. 2.5 这种才是正确的表达
float 的演算也是自己的符号 +. –. *. /.
5.2
对等的表达式的类型必须相同,比如if的分支,和c语言作一个简单的比较
(* C *)
int lucky(){
int r;
while (1){
r = rand() % 100;
if (r == 50)
return r;
else
printf(“again/n”)
}
}
C的else 是一个printf
(* OCaml *)
let rec lucky () =
let r = Random.int 100 in
if r = 50 then
r
else
(printf(“again/n”); lucky())
但是在ocaml 里面else里面也必须是和r 对等的表达式
6.List
相同类型value的排列
第一个element和后面的elements分开
[1;2;3] = 1::[2;3] = 1::2::[3]
[“a”] = “a”::[]
let ilist1 = [1; 2; 3]
let ilist2 = 4::ilist1
let ilist3 = ilist1@ilist2 //连接两个list
let getHead l =
match l with
h::t –> h //h::t 表示一个list type
| [] -> raise Error
8.tuple
可以是各种类型的value的组合
let man = (“age”,24)
let input = (10,100,(fun x->x * x))
let get?rst l =
match l with
(f, _, _) –> f
9.record
标有名字的value的组合,和c语言的Struct比较相似
type subject = {name : string; credit : int}
let getName r =
match r with
{name= n; credit = c} –> n
10. 自定义类型
可以方便的定义各种类型
给已经存在的type 新的名字标示
type value = int
type tree = Leaf | Node of value * tree * tree
(tree 是一个type, 可以具有Leaf 或者Node )
let t = Node (5, Leaf, Node (4, Leaf, Leaf))
let rec sum t =
match t with
Node (v, t1, t2) -> v + sum t1 + sum t2
| Leaf –> 0
10.1 自定义type的多样性
type itree = Leaf of int
| Node of int * itree * itree
type ‘a tree = Leaf of ‘a
| Node of ‘a * ‘a tree * ‘a tree
let a = Leaf 5
let b = Node(“b”,Leaf”l”,Leaf”r”)