# 二分探索木を用いたテーブルの定義

# module type TABLE = sig type ('a, 'b) t val empty : ('a, 'b) t val add : 'a -> 'b -> ('a, 'b) t -> ('a, 'b) t val retrieve : 'a -> ('a, 'b) t -> 'b option val dump : ('a, 'b) t -> ('a * 'b) list end;; module type TABLE = sig type ('a, 'b…

# 任意精度の有理数計算によるNewton-Raphson法

# open Num;; # (* f'(x)を求める *) let deriv f = let dx = Int 10 **/ Int (-50) in fun x -> (f (x +/ dx) -/ f x) // dx;; val deriv : (Num.num -> Num.num) -> Num.num -> Num.num = <fun> # (* f(x), f(f(x)), f(f(f(x))), ..., を計算していき、ステップ</fun>…

# 書き換え可能なデータ構造を使ったキュー

いつもの如くまずは型の定義。 # type 'a mlist = MNil | MCons of 'a * 'a mlist ref;; type 'a mlist = MNil | MCons of 'a * 'a mlist ref # type 'a queue = {mutable head : 'a mlist; mutable tail : 'a mlist};; type 'a queue = { mutable head : 'a…

# unit型を使った無限数列

# type 'a seq = Cons of 'a * (unit -> 'a seq);; type 'a seq = Cons of 'a * (unit -> 'a seq) # let rec from n = Cons (n, fun () -> from (n+1));; val from : int -> int seq = <fun> # let rec take n (Cons (x, f)) = if n > 0 then x :: take (n-1) (f </fun>…

# 素数の無限数列

# let rec prime_seq primes x = let x' = x + 1 in let rec is_prime n = function [] -> true | p :: rest -> p*p <= x' && n mod p <> 0 && is_prime n rest in if is_prime x' primes then Cons (x', prime_seq (x' :: primes)) else prime_seq primes x…