To use those definition in GHCi exactly as they were written (i.e. with multiple equations or type signatures in separate lines), you need to use multiline input in GHCi through the :{
and :}
delimiters:
GHCi> :{
GHCi| foo 0 = print 999
GHCi| foo n = print n
GHCi| :}
GHCi> foo 0
999
One alternative would be turing on multiline input for the rest of your session with the +m
option. In this case, though, you also need an explicit let
, as without it GHCi won't figure out 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 turn +m
off with :unset +m
.)
Yet another possibility is eschewing line breaks altogether, and using explicit braces and semicolons:
GHCi> foo 0 = print 999; foo n = print n
GHCi> foo 0
999
Between the multiline input options, I personally prefer :{
and :}
over +m
, as they require less changes with respect to how I usually phrase my definitions, and are more likely to work straight away if I paste code from somewhere else.
As for why your way of entering it didn't work, it was because, unless you use multiline input, bindings to the same name in separate GHCi lines shadow each other:
GHCi> x = 3
GHCi> x = 4
GHCi> x
4
This seems less surprising if we note that we get the same behaviour from a chain of let
-expressions:
GHCi> let x = 3 in let x = 4 in x
4
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…