What's an elegant way to write the classic take
function in CameLIGO?
take
takes the first num
elements of a list.
This is how I'm writing it currently, and it's ugly.
Here, message
is a type I defined:
let rcons((xs, x): message list * message): message list =
x :: xs
let reverse (xs: message list): message list =
List.fold rcons xs ([]: message list)
let takeReverse ((num, xs): nat * message list): message list =
let accumulate ((taken, x): message list * message) =
if List.length taken < num then
x :: taken
else
taken
in
List.fold accumulate xs ([]: message list)
// This is such an ugly construction.
let take ((num, xs): nat * message list): message list =
let reversed = takeReverse (num, xs) in
reverse reversed
Basically, to write take
I'm reversing the list twice.
I could write it more succinctly if I had non-tail recursion, but alas that's not offered by LIGO.
Thanks!