I try to go through a list xl
by List.fold_left
, I would like to quit the iteration when some condition is satisfied:
List.fold_left
(fun x acc ->
if x = 5 then STOP THE ITERATION
else x + acc)
xl
Could anyone tell me how to express STOP THE ITERATION
here? Thank you
Edit1: By the code above, I would like to say we do not stop accumulation until we meet the first 5
.
You cannot do this with the built in folds without an exception or some no-op being flagged in the accumulator for the remaining calls --as phimuemue mentions. Alternatively, you can just write a very simple tail-recursive function to take care of returning early,
(** Fold left on a list with function [f] until predicate [p] is satisfied **)
let rec fold_until f p acc = function
| x :: xs when p x -> acc
| x :: xs -> fold_until f p (f acc x) xs
| [] -> acc
let accum_until_five =
fold_until (fun acc x -> x + acc) (fun x -> x = 5) 0
Therefore, you'll have to encode the condition into your x
argument of the inner function:
let t l =
let (a,b) =
List.fold_left
(fun ((accx, condition) as acc) x ->
if condition then acc else (x+accx, x=5))
(0,false) l
in
a;;
That is, you have to tell your function that - once the 5 has been seen - it should simply return the stuff it has done up to now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With