I’m reading “Get programming with Haskell”, from Will Kurt. At the end of Lesson 3, which is about lexical scope, the author writes:
Using a
letexpression and a lambda function aren’t exactly the same thing under the hood. For example, the following code will cause an error if you try to run it:counter x = let x = x + 1 in let x = x + 1 in xTo prove that
letand lambda aren’t identical, rewrite the counter function exactly as it is here, but use nested lambdas instead oflet.
Here’s my solution, which works as I expect it to do:
counterLambda x = (\x -> (\x -> x) (x + 1)) (x + 1)
-- counterLambda 2 == 4
However, as the author suggests, if I run counter 2 in ghci, it hangs forever (using GHC 8.8.3).
What’s happening under the hood?
PS: It works when I properly name the variables.
counter x = let a = x + 1 in let b = a + 1 in b
-- counter 2 == 4