Ocaml 과제한거
No 1.
# let rec empty l = match l with
[] -> true
| _::_ -> false;;
val empty : 'a list -> bool = <fun>
# empty [1;2;3];;;
- : bool = false
#
No 2.
# let rec sum l = match l with
[]->0
|h::tl -> h+(sum tl);;
val sum : int list -> int = <fun>
# sum [2;3;4];;
- : int = 9
#
No 3.
# let rec square l = match l with
[]->[]
| h::tl -> h*h::(square tl);;
val square : int list -> int list = <fun>
# square [1;2;3;4;];;
- : int list = [1; 4; 9; 16]
#
No 4.
# let rec runnerup l = match l with
h::h2::[] -> if h>h2 then h2 else h
|h::h2::h3::tl -> if h2>h then runnerup (h2::h::h3::tl)
else if h3>h then runnerup (h3::h::tl)
else if h3>h2 then runnerup (h::h3::tl)
else runnerup (h::h2::tl)
|[]|_::_ -> 0;;
val runnerup : int list -> int = <fun>
#
# runnerup[5;2;3;4];;
- : int = 4
#
No 5.
No 6.
# type bintree = Leaf | Node of bintree * int * bintree;;
type bintree = Leaf | Node of bintree * int * bintree
# Leaf;;
- : bintree = Leaf
# let rec symtree t = match t with
Leaf -> Leaf
|Node (l,v,r) -> Node(symtree r, v, symtree l);;
val symtree : bintree -> bintree = <fun>
# let a = Node(Node(Leaf,2,Leaf),1,(Node(Node(Leaf,4,Leaf),3,Node(Leaf,5,Leaf))));;
val a : bintree =
Node (Node (Leaf, 2, Leaf), 1,
Node (Node (Leaf, 4, Leaf), 3, Node (Leaf, 5, Leaf)))
# symtree a;;
- : bintree =
Node (Node (Node (Leaf, 5, Leaf), 3, Node (Leaf, 4, Leaf)), 1,
Node (Leaf, 2, Leaf))
#
No 7.
# type formula = T
|F
|Conj of formula * formula
|Disj of formula * formula
|Impl of formula * formula
|Neg of formula;;
type formula =
T
| F
| Conj of formula * formula
| Disj of formula * formula
| Impl of formula * formula
| Neg of formula
# let rec truth = function
|T->T
|F->F
|Conj(f1, f2) -> if (truth f1)=F then F else(truth f2)
|Disj(f1, f2) -> if (truth f1)=T then T else(truth f2)
|Impl(f1, f2) -> if (truth f1)=T then T else F
|Neg (f) -> if (truth f)=T then F else T;;
val truth : formula -> formula = <fun>
# truth (Impl(Disj(T,F), Conj(T,F)));;
- : formula = T
#
No 8.
# type nat = O | S of nat;;
type nat = O | S of nat
# let rec add m = function
O->m
|S n-> add (S m) n;;
val add : nat -> nat -> nat = <fun>
# add (S (S O)) (S (S (S O)));;
- : nat = S (S (S (S (S O))))
# let rec mul a b = match b with
O -> O
| S n -> add (mul a n) a ;;
val mul : nat -> nat -> nat = <fun>
# mul (S(S O)) (S(S O));
;;
- : nat = S (S (S (S O)))
# mul (S(S(S O))) (S(S O));;
- : nat = S (S (S (S (S (S O)))))
# let rec sub m n = match m,n with
O,O -> O
|S n, S n2 -> sub n n2
|S n, O -> m
|O , S n -> raise Not_found;;
val sub : nat -> nat -> nat = <fun>
# sub (S (S (S O))) (S O);;
- : nat = S (S O)
# let rec div a b = match a with
O -> O
|S n -> try add (div ( sub a b ) b ) (S O) with _-> O;;
val div : nat -> nat -> nat = <fun>
# div (S(S(S(S O )))) (S (S O));;
- : nat = S (S O)
# div (S(S(S O))) (S (S O));;
- : nat = S O
#
'Programing 미분류' 카테고리의 다른 글
Wiimote를 이용한 헤드트래킹 프로그램 (0) | 2009.07.03 |
---|---|
ocaml 연습. (0) | 2009.03.20 |
태희 강의 (0) | 2009.03.13 |