Skip to content

Instantly share code, notes, and snippets.

@yuga
Last active December 9, 2015 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuga/4316050 to your computer and use it in GitHub Desktop.
Save yuga/4316050 to your computer and use it in GitHub Desktop.
今朝流行ってた

Haskell:

fold_left f i []      -> i
fold_left f i (x:xs') -> fold_left  f (f i x) xs'

fold_right f []      i = i
fold_right f (x:xs') i -> f x (fold_right f xs' i)

fold_right' f xs i = go id xs
  where
    go g [] = g i
    go g (x:xs') = go (g . (f x)) xs'
    -- go g (x:xs') = go (\i' -> g (f x i')) xs'

OCaml:

let rec fold_left  f i xs = match xs with
  | [] -> i 
  | x::xs' -> fold_left f (f i x) xs';;

let rec fold_right f xs i = match xs with
  | [] -> i
  | x::xs' -> f x (fold_right f xs' i);;

let fold_right' f xs i =
  let rec go g xs' = match xs' with
    | [] -> g i 
    | x::xs'' -> go (fun i' -> g (f x i')) xs'' 
  in go (fun j -> j) xs;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment