10

I'm logging the a and b values of a foldl.

words = ["mate", "bro", "bruv"]

sum2 = List.foldl
    (\a b ->
        Debug.log(toString <| a)
        Debug.log(toString <| b)
        a
    ) "guv" words

It works as expected, but I can't understand the output:

"mate": <function>
"guv": "mate"
"bro": <function>
"mate": "bro"
"bruv": <function>
"bro": "bruv"

Why is it outputting a as a <function>, and what is it outputting b as a:b ?

Rich
  • 5,603
  • 9
  • 39
  • 61

1 Answers1

12

Debug.log takes two arguments, a tag string, which can be anything, and then the value to be logged. Updating your code like this might work:

words = ["mate", "bro", "bruv"]

sum2 = List.foldl
    (\a b 
        Debug.log "Value of a: " a
        Debug.log "Value of b: " b
        a
    ) "guv" words

Although, come to think of it, I think you need to do a bit of a trick for logging values that you don't want to return, like so:

words = ["mate", "bro", "bruv"]

sum2 = List.foldl
    (\a b ->
        let
            _ = Debug.log "Value of a: " a               
            _ = Debug.log "Value of b: " b
        in
            a
    ) "guv" words
dontexist
  • 5,252
  • 4
  • 27
  • 51
  • That works, interesting! Is there a rule in Elm that you can't have statements that don't get saved to variable? E.g. `Debug.log "Value of a: " a ` doesn't work without the `logA =` – Rich Apr 10 '17 at 10:43
  • 2
    Yes, since Elm is (almost) purely functional, you can't have any side-effects, but since `Debug.log` is one of the exceptions to that rule, you still have to trick the Elm compiler. Usually, when you're only logging a single value, you use `_` instead of `logA` to indicate that it's a throw-away variable. – dontexist Apr 10 '17 at 11:12
  • 3
    You can use `_` for both, it actually means throwaway to the compiler, rather than just a value that happens to be named `_` (see an example at https://ellie-app.com/Swtbcn7wNpa1/0) – bdukes Apr 10 '17 at 12:45
  • Oh, I didn't know that, that's great. – dontexist Apr 10 '17 at 12:53