I'm new to functional programming (ReasonML / OCaml).
I have a list of floats. I want to get the first three non-zero items of a list and no more. Items can be positive, negative, and zero.
How can recursion be limited until the first three non-zero floats are extracted?
I was thinking of doing something like:
switch (list) {
| [first, second, third, ...rest] => (first +. second +. third) /. 3.0
| _ => 0.0
};
But how can I guarantee that first
, second
, and third
are non-zero floats? And if they are, discard them recursively until three non-zero floats are found -- or return 0.0
.
A nicer way to do this using recursion is to make it more generic: instead of finding the 3 first non-zero, let's find the
n
first non-zero.Below is an OCaml implementation, I don't know Reason.
Here's the function's signature:
There's a lot going on here, but it's not that bad. The logic here is the following:
Everything else is just additional logic:
A word about tail-recursion
Unfortunately, the above implementation is not tail-recursive, which means it will fail on large lists. A common technique to make a function tail-recursive is to use an accumulator (
acc
in the code below) to store the intermediate result.Then, we encapsulate this extra logic in a local helper function (often called
loop
oraux
) so that the accumulator doesn't show up in the function's signature.