Search code examples
elmfoldleft

Elm: How to log inside a foldl


I have the following code:

findPerson name peeps = List.foldl
    (\a b -> case b of
        Just _ -> b
        Nothing -> if a.name == name then
            Just a
            else Nothing
    ) Nothing peeps

I would like to log the values of a and b inside the foldl. I've tried:

findPerson : String -> List Person -> Maybe Person
findPerson name peeps = List.foldl
    (\a b ->
        Debug.log(a)
        Debug.log(b)
        case b of
            Just _ -> b
            Nothing -> if a.name == name then
                Just a
                else Nothing
    ) Nothing peeps

However, this throws an error

I am looking for one of the following things:

a closing paren ')'
whitespace`

What am I doing wrong, and how can I log the values inside foldl?


Solution

  • You can use a let in block for debugging.

    let
        _ = Debug.log "a" a
        _ = Debug.log "b" b
    in
        case b of
    ...
    

    A function (or lambda) can only return once. Debug.log returns the second argument unchanged, so you have to pattern match it against something - and because you don't need the argument twice, but the side effect of Debug.log, you can pattern match it against _ (ignore).