Search code examples
haskellfold

Why doesn't foldr const 0 "tacos" Compile in Haskell?


So foldr const 0 "tacos" should unravel to be something like

0 const ('t' const ('a' const ('c' const ('o' const 's')))). 

I think it would just stop at 0 const ('t' though because Haskell is lazy evaluated and const just takes the first argument. So, in theory, wouldn't the function turn out to apply to 1?

This doesn't work though. And replacing 0 with "" doesn't work either. Does anyone know why?

Thank you!


Solution

  • I'm guessing you made two errors: one small and one slightly less small.

    1. To use a variable with letters (such as const) as an operator, you must enclose it in backticks:

      "hello" `const` 1 = "hello"
      "hello" const 1 -- nonsense
      
    2. You partially mixed up foldr with foldl:

      foldr (#) n [1..3] = 1 # (2 # (3 # n))
      foldl (#) b [1..3] = ((b # 1) # 2) # 3
      

    Indeed, foldl works just fine with const:

    foldl const 0 "tacos"
      = ((((0 `const` t) `const` a) `const` c) `const` o) `const` s
      = 0
    

    This silly calculation is rather inefficient—it needs to walk the whole list to apply const 0 to each element, even though the result is always the same!