Created
September 4, 2017 18:37
-
-
Save l1x/c7883f40f03c7d66b118d490ee6fd2f6 to your computer and use it in GitHub Desktop.
Trying to implement Clojure functions in OcaML
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 range ~small:a ~big:b = | |
let rec range_aux ~small:a ~big:b ~accumulator:acc = | |
if a > b then acc | |
else range_aux ~small:(a+1) ~big:b ~accumulator:(a :: acc) in | |
List.rev (range_aux ~small:a ~big:b ~accumulator:[]) | |
let take ~list:l ~count:n = | |
if List.length l <= n | |
then l | |
else | |
let rec take_aux ~list:l ~count:n ~acc:acc = | |
let len = List.length acc in | |
match l, len with | |
| _, len when len = n -> List.rev acc | |
| [], _ -> [] | |
| h :: t, _ -> take_aux ~list:t ~count:n ~acc:(h :: acc) in | |
take_aux ~list:l ~count:n ~acc:[] | |
let drop ~list:l ~count:n = | |
if List.length l < n | |
then [] | |
else | |
let rec drop_aux ~list:l ~count:n = | |
match l, n with | |
| l, 0 -> l | |
| h :: t, n -> drop_aux ~list:t ~count:(n-1) in | |
drop_aux ~list:l ~count:n | |
(* | |
This function does not support overlapping partitions | |
https://github.com/clojure/clojure/blob/clojure-1.9.0-alpha14/src/clj/clojure/core.clj#L3157 | |
*) | |
let partition ~list:l ~partition_size:s = | |
let rec partition_aux ~list:l ~partition_size:s ~acc:acc = | |
match l, acc with | |
| [], acc -> List.rev acc | |
| l, acc -> partition_aux ~list:(drop ~list:l ~count:s) ~partition_size:s ~acc:((take ~list:l ~count:s) :: acc) in | |
partition_aux ~list:l ~partition_size:s ~acc:[] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment