Why does this Haskell code never end?

I recently wrote some Haskell code and it never ends. After I carefully studied my code, the problem boiled down to the following code fragment

main :: IO () main = print $ let a = 10 in let a = a in a :: Int 

I guess this should have something to do with Haskell laziness, since the same code ends in OCaml. However, if I wrote the following code instead

 main :: IO () main = print $ let a = 10 in let b = a in b :: Int 

the code would have no problems with completion. I can’t understand the reason, because in the source code there are two and should be considered as two different variables. I do not know why their names have anything to do with the semantics of the program.

+5
source share
2 answers

The problem is that, unlike OCaml, let bindings in Haskell are recursive by default. Thus, let x = x in ... equivalent to OCaml let rec x = x in ... and is a circular definition.

That's why shadowing variable names in Haskell (i.e. defining a several times) is considered bad style and even has a compiler warning that you can turn on with the -Wall flag or, more specifically, -fwarn-name-shadowing .

This default value makes more sense in Haskell than OCaml, because laziness makes circular values ​​(and not just recursive functions) really useful. let x = 1:x gives us an infinite list 1 , which we can use as a regular list.

At the same time, some people do not like this mainly for the reason you came across here: it is possible to introduce non-intuitive endless loops into your code, which makes it difficult to track errors and typos. This is also confusing, because if necessary, <- bindings in do-notation are not recursive by default, which is a bit inconsistent.

+15
source

The second binding ( a = a ) obscures the other. The first example is (almost) exactly equivalent

 main = print $ let xyz = 10 in let a = a in a :: Int 

and I hope it’s clear why it doesn’t end! You can get the GHC to alert you to this by using the -fwarn-name-shadowing flag (or by typing :set -fwarn-name-shadowing in GHCi)

+5
source

Source: https://habr.com/ru/post/1206746/


All Articles