Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Trying to implement Clojure functions in OcaML
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