I’ve got a function that uses List.fold_left2 to check if a list is a palindrome. (Use of fold isn’t optional: this is a homework problem.)
let is_p lst =
List.fold_left2 (fun acc e1 e2-> if (e1=e2) then acc else false) true lst (List.rev lst)
But I’d like to optimize it. What’s the best way to return ‘false’ as soon as one mismatch is found?
I’d rather not throw exceptions, but I realize that might be the best answer. I’ve also considered changing the anonymous function to:
fun acc e1 e2-> if (not acc) then false else (if (e1=e2) then acc else false)
Either use an exception, or “unroll” the fold into a custom recursive function. The fold pattern always traverses the complete list.
Be sure to benchmark both, as exception handling can be an expensive operation in some languages (I’m not sure if this is true of OCaml).