How to make errors bubble up quickly?

Hello,

say I have a List String that I want to transform into a List Int.
In an imperative language, I would use a for loop and at the first string that can’t be converted into an int, I would throw an exception.
But how would I achieve something similar in Elm?

I think I’d like to write a function that has this signature:

mapOrFail : (a -> Maybe b) -> List a -> Maybe (List b)

If all the values in the first list map to Just variants, then all is good and a Just (List b) is returned.
But at the first value that maps to a Nothing, no more computation would be done and I would get Nothing returned from the whole function.
How would you achieve that? I guess I would have to use some kind of lazy functionality of the language?

Elm has no lazyness. You can do what you want with recursion:

mapOrFail toMaybeB theAs =
    mapOrFailHelper toMaybeB [] theAs

mapOrFailHelper toMaybeB reversedBs theAs =
    case theAs of
        [] -> Just (List.reverse reversedBs)
        a::otherAs ->
            case toMaybeB a of
                   Just b -> mapOrFailHelper toMaybeB  (b :: reversedBs) otherAs
                   Nothing ->  Nothing

It is a bit entangled since you want stop the computation as soon as possible. Feel free to ask for clarification.

2 Likes

Excellent, thank you!