Skip to content

Instantly share code, notes, and snippets.

@musha68k
Last active April 2, 2017 20:33
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 musha68k/3fa33fff51db4f6818dfd226df7fbe10 to your computer and use it in GitHub Desktop.
Save musha68k/3fa33fff51db4f6818dfd226df7fbe10 to your computer and use it in GitHub Desktop.
List operations
let rec fold ~init ~f = function
[] -> init
| x :: xs -> fold ~init:(f init x) ~f xs
let length xs =
xs
|> fold ~init:0 ~f:(fun acc _ -> acc + 1)
let reverse xs =
xs
|> fold ~init:[] ~f:(fun acc x -> x :: acc)
let append xs ys =
xs
|> reverse
|> fold ~init:ys ~f:(fun acc x -> x :: acc)
let map ~f xs =
xs
|> reverse
|> fold ~init:[] ~f:(fun acc x -> f x :: acc)
let filter ~f xs =
xs
|> reverse
|> fold ~init:[] ~f:(fun acc x -> if f x then x :: acc else acc)
let concat xs =
xs
|> reverse
|> fold ~init:[] ~f:(fun acc x -> append x acc)
let rec fold ::init ::f =>
fun
| [] => init
| [x, ...xs] => fold init::(f init x) ::f xs;
let length xs =>
xs
|> fold init::0 f::(fun acc _ => acc + 1);
let reverse xs =>
xs
|> fold init::[] f::(fun acc x => [x, ...acc]);
let append xs ys =>
xs
|> reverse
|> fold init::ys f::(fun acc x => [x, ...acc]);
let map ::f xs =>
xs
|> reverse
|> fold init::[] f::(fun acc x => [f x, ...acc]);
let filter ::f xs =>
xs
|> reverse
|> fold
init::[]
f::(fun acc x => if (f x) { [x, ...acc] } else { acc });
let concat xs =>
xs
|> reverse
|> fold init::[] f::(fun acc x => append x acc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment