Haskellのリスト操作をOCamlに移植(2)

30分プログラム、その343。昨日に引き続き、http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.htmlの関数をOcamlに移植。OCamlってtakeもないんだぜ・・。

使い方

# take 3 [1;2;3;4;5];;
- : int list = [1; 2; 3]
# drop 3 [1;2;3;4;5];;
- : int list = [4; 5]

ソースコード

let maximum xs =
  fold_left1 max xs

let minimum xs =
  fold_left1 min xs

let rec scanl f y =
  function
      [] ->
	[y]
    | x::xs ->
	y::scanl f (f y x) xs

let scanl1 f =
  function
      [] ->
	[]
    | x::xs ->
	scanl f x xs

let rec scanr f z =
  function
      [] ->
	[z]
    | x::xs ->
	let y::_ as yss = 
	  scanr f z xs in
	  (f x y) :: yss

let scanr1 f =
  function
    [] -> 
      []
  | x::xs -> 
      scanr f x xs

let replicate n x =
  let rec loop i ys = 
    if i = 0 then
      ys
    else
      loop (i-1) (x::ys) in
    loop n []
    
let rec take n =
  function
      [] ->
	[]
    | x::xs ->
	if n <= 0 then
	  []
	else
	  x :: take (n - 1) xs

let rec drop n =
  function
      [] ->
	[]
    | xs when n <= 0 -> 
	xs
    | x::xs -> 
      drop (n-1) xs