Last active
April 2, 2017 20:33
-
-
Save musha68k/3fa33fff51db4f6818dfd226df7fbe10 to your computer and use it in GitHub Desktop.
List operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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