Function definition by special cases in GHCi

From the Haskell tutorial :

We can write integer functions on cases.

-- Compute the sum of the integers from 1 to n. sumtorial :: Integer -> Integer sumtorial 0 = 0 sumtorial n = n + sumtorial (n-1) 

However, what happens when I try to do this:

 $ ghci GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help Prelude> foo 0 = print 999 Prelude> foo n = print n Prelude> foo 0 0 

What am I missing?

+5
source share
2 answers

In order to use your definition in GHCi exactly as you wrote it (i.e. with several equations in separate lines), you need to use multi-line input in GHCi through delimiters :{ and :} :

 GHCi> :{ GHCi| foo 0 = print 999 GHCi| foo n = print n GHCi| :} GHCi> foo 0 999 

Alternatively, you could use multi-line input for the rest of the session with the +m option. In this case, however, you also need an explicit let , since without it, GHCi will not figure out that you want to continue the definition:

 GHCi> :set +m GHCi> let foo 0 = print 999 GHCi| foo n = print n GHCi| GHCi> foo 0 999 

(You can disable +m with :unset +m .)

Another possibility is to discard line breaks altogether and use explicit brackets and semicolons:

 GHCi> foo 0 = print 999; foo n = print n GHCi> foo 0 999 

Between multi-line parameters, I personally prefer explicit delimiters over +m , as this requires less changes in the way I usually express my definitions, and is more likely to start working immediately if I paste the code from another place.

As for why your input method didn't work, it was because if you don't use multi-line input, bindings with the same name on separate GHCi lines will shadow each other:

 GHCi> x = 3 GHCi> x = 4 GHCi> x 4 

This seems less unexpected when you consider that we get the same behavior from a chain of let expressions:

 GHCi> let x = 3 in let x = 4 in x 4 
+15
source

ghci is an interactive tool and, as such, allows you to override a function when it is already defined. In your case, this is not considered as a definition of a function of two lines, but as two attempts to determine it. Thus, fn = print n redefines f 0 = print 999 , but does not complete it.

To introduce a multi-line operator in ghci, there is a special syntax. You need to do

 Prelude> :{ Prelude> let foo 0 = print 999 Prelude> foo n = print n Prelude> :} 
+2
source

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


All Articles