[Haskell-beginners] A very counterintuitive behaviour of Haskell

Daniel Fischer daniel.is.fischer at googlemail.com
Thu Jan 27 16:07:21 CET 2011


On Thursday 27 January 2011 15:55:58, Renzo Orsini wrote:
> In studying Haskell, I produced the following output from GHC:
>
> xxx-3:~ xxx$ GHCi
> GHCi, version 6.12.3: http://www.haskell.org/ghc/  :? for help
> Loading package ghc-prim ... linking ... done.
> Loading package integer-gmp ... linking ... done.
> Loading package base ... linking ... done.
> Loading package ffi-1.0 ... linking ... done.
> Prelude> let f 7 = "ok"
> Prelude> let f x = "no"
> Prelude> f 3
> "no"
> Prelude> f 7
> "no"
>
>
> I suppose it is correct. However, for someone who is interested in the
> language, it seems very counterintuitive... Somebody would be so kind to
> explain to a neophyte this "feature" of the language?

It's not a feature of the language, it's a feature of the interpreter.
In ghci's own words (evoked by the -Wall flag):

Prelude> let f 7 = "ok"

<interactive>:1:5:
    Warning: Pattern match(es) are non-exhaustive
             In an equation for `f':
                 Patterns not matched: #x with #x `notElem` [7#]
Prelude> let f x = "no"

<interactive>:1:5:
    Warning: This binding for `f' shadows the existing binding
               bound at <interactive>:1:5

<interactive>:1:7: Warning: Defined but not used: `x'


You have defined two independent functions, the second overwriting the 
first binding.
To get what you wanted, you have to put the branches on the same line, 
separated by a semicolon:

Prelude> let f 7 = "ok"; f _x = "no"
(0.02 secs, 3348380 bytes)
Prelude> f 3
"no"
(0.01 secs, 1962728 bytes)
Prelude> f 7
"ok"

(I prefixed the x with an underscore in the second equation to preven an 
"unused variable" warning, could also have used the wildcard _).

>
> Thank you very much.
>
> Renzo

Cheers,
Daniel



More information about the Beginners mailing list