unfold で1から10までのリスト

unfold を覚えたので,こないだの1から10までのリストを unfold を使ってやってみる。
と思ったら unfold が見つからないのでまずはその定義から。

 # let rec unfold f init =
     match f init with
       Some (a, b) -> a :: unfold f b
     | None        -> []
   ;;
 val unfold : ('a -> ('b * 'a) option) -> 'a -> 'b list = <fun>

で,リストを作る関数。

 # let list_of_int i j =
     unfold (fun x -> if x + 1 = j then None else Some (x, x+1)) i
   ;;
 val list_of_int : int -> int -> int list = <fun>
 # list_of_int 1 10;;
 - : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]