(* Viele Listenoperationen lassen sich auf fold_left zurueckfuehren *) (* L. Fellermayr (leo@slacky.de) *) let rec foldl f s = function (* fold left *) [] -> s | x::xs -> foldl f (f x s) xs ;; let rec foldr f s = function (* fold right *) [] -> s | x::xs -> f x (foldr f s xs) ;; (* Uses *) let length = foldl (fun a b -> b+1) 0 ;; let rev = foldl (fun a b -> a::b) [] ;; let append x y = foldr (fun a b -> a::b) y x ;; let map f = foldr (fun x y -> (f x)::y) [] ;; let filter f = foldr (fun x y -> if (f x) then x::y else y) [] ;; let member e = foldr (fun x y -> if x = e then true else y) false ;; let count e = foldr (fun x y -> if x = e then y+1 else y) 0 ;; (* Dezimalzahldarstellung einer natuerlichen Zahl als Liste (num2dec) *) let dec = let rec dec_aux acc n = if (n < 10) then n::acc else let rest = n mod 10 and ganz = n / 10 in dec_aux (rest::acc) ganz in dec_aux [] ;; (* Liste der Dezimalzahldarstellung als natuerliche Zahl (dec2num) *) let num = foldl (fun x y -> x+y*10) 0 ;;