落書きノート

ふと自分が気になった事を書いてます

OCamlの学習

えーと、何回目ですかね。分かりませんが、今日はこんな感じです。試すプログラムが少なかったのですが、今回の項目は難しいですね。練習問題が難しくなりそうです。

        OCaml version 4.03.0

# let rec fact n = if n = 1 then 1 else fact(n-1) * n;;
val fact : int -> int = <fun>
# fact 4;;
- : int = 24
# fact (-1);;
Stack overflow during evaluation (looping recursion?).
# let rec x = x * x + 1;;
Error: This kind of expression is not allowed as right-hand side of `let rec'
# let square x = x * x;;
val square : int -> int = <fun>
# let zero (x : int) = 0;;
val zero : int -> int = <fun>
# #trace fact;;
fact is now traced.
# fact 4;;
fact <-- 4
fact <-- 3
fact <-- 2
fact <-- 1
fact --> 1
fact --> 2
fact --> 6
fact --> 24
- : int = 24
# #untrace fact;;
fact is no longer traced.
# fact 5;;
- : int = 120
# let rec fib n = if n = 1 || n = 2 then 1 else fib(n - 1) + fib(n - 2);;
val fib : int -> int = <fun>
# let rec fib_pair n = if n = 1 then (1, 0) else let (i, j) = fib_pair (n - 1) in (i + j, i);;
val fib_pair : int -> int * int = <fun>
# let fib n = let (i, _) = fib_pair n in i;;
val fib : int -> int = <fun>
# let fib n = let rec fib_pair n = if n = 1 then (1, 0) else let (i, j) = fib_pair (n - 1) in (i + j, i) in let (i, _) = fib_pair n in i;;
val fib : int -> int = <fun>