Strange Behavior in GHCi

I wrote the following code snippet:

it :: Int -> Int it n | n < 1 = error "Invalid entry." | n == 1 = 0 | otherwise = 1 + it (n `quot` 2) 

When I upload it to GHCi, something strange happens. The first time I call the it function, it works fine and returns the expected results. However, the next time I get the following failure:

 λ: :t it it :: Int -> Int λ: it 2 1 λ: it 2 <interactive>:4:1: Couldn't match expected type `a0 -> t0' with actual type `Int' The function `it' is applied to one argument, but its type `Int' has none In the expression: it 2 In an equation for `it': it = it 2 λ: :t it it :: Int λ: it 1 

It seems that the type it somehow changes after the first call. Things get even weirder when it is called several times from main , i.e. all calls return the expected results, but at the end () is assigned as type it :

 main :: IO () main = do let r1 = it 1 r2 = it 2 r3 = it 3 print r1 print r2 print r3 λ: main 0 1 1 λ: :t it it :: () 

I believe that this is a mistake related to the identifier it and the internal elements of GHCi, since renaming the function to something else (like it' ) completely solves the problem. Moreover, the body of the function does not seem to have any effect; doing let it = (+) 2 and evaluating it several times is also problematic.

Any insight would be appreciated. The output of ghci --version is "version 7.6.3".

+5
source share
1 answer

Invalid name: it - this GHCi name is automatically associated with the result of your previous evaluation, so you can easily reference it again. Thus, your first use immediately restores it, overshadowing your definition.

If it defined in a module, you can still reliably reference it with GHCi using a module prefix, for example. Main.it

+11
source

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


All Articles