ocaml 연습.

Programing 미분류 : 2009. 3. 20. 02:38
반응형

# let rec cut i l ll = match i with
  0 -> ll
  | n -> cut (i-1) (List.tl l) ll@[List.hd l];;
val cut : int -> 'a list -> 'a list -> 'a list = <fun>

# let rec insertr x y z = match z with
  [] -> []
  | h::tl -> if x=h then [h;y]@(insertr x y tl) else [h]@(insertr x y tl);;

# let rec last a = match a with
  [] -> raise Not_found
  h::tl -> if tl=[] then h else last tl;;

# let a = 1::2::3::4::5::[];;
val a : int list = [1; 2; 3; 4; 5]

# let rec increment x = match x with
  [] -> []
  | h::tl -> [(h+1)]@increment tl;;

# let rec increment x = match x with
  [] -> raise Not_found
  | h::tl -> if tl=[] then [h+1]
             else [h+1]@(increment tl) ;;

# let rec remove x y  = match y with
  [] -> []
  | h::tl -> if x=h then (remove x tl) else [h]@(remove x tl);;

# let rec count_between m n  = match n with
  n -> if n=m then [] else [m]@(count_between (m+1) n);;

# let rec zip x y  = match x with
  [] -> []
  | x -> [(List.hd x),(List.hd y)]@zip(List.tl x) (List.tl y);;

# let rec sum_to x = match x with
  0 -> 0
  | n -> sum_to (n-1)+n;;

# let rec occurs x l = match l with
  [] -> 0
  | h::tl -> if h=x then 1+(occurs x tl) else occurs x tl;;

# let rec mapit f l = match l with
  [] -> []
  | h::tl -> [f h]@(mapit f tl);;

# let rec triple l = match l with
  [] -> []
  | h::tl -> h::h::h::[]@(triple tl);;

# let rec append x y = match x with
  [] -> begin match y with
              [] -> []
              | h::tl -> h::append [] tl
        end
  | h::tl -> h::append tl y;;

# let rec fact x = match x with
  0 -> 1
  | n -> n*(fact (n-1));;

# let rec fib x = match x with
  0 -> 0
  |1 -> 1
  |n -> fib(n-2)+fib(n-1);;

# let rec even x = if x mod 2 = 0 then true else false
  and odd x = if x mod 2 = 1 then true else false;;

# let fib n =
     let rec fib' i p q =
        if i = n then p
        else fib' (i+1) (p+q) p
     in
     if n = 1 then 1
     else fib' 2 1 1;;
반응형

'Programing 미분류' 카테고리의 다른 글

Ocaml 과제한거  (0) 2009.04.08
태희 강의  (0) 2009.03.13
Fixed Point Coding  (0) 2009.02.15
Posted by Real_G