[Haskell-beginners] about the pattern matching

Daniel Fischer daniel.is.fischer at web.de
Tue Dec 23 21:39:52 EST 2008


Am Mittwoch, 24. Dezember 2008 02:45 schrieb Raeck Zhao:
> hi, good ... morning : )
> I am just confused by the following code
>
> > oneOnly :: [Int]
> > oneOnly = [1]
> > isOneOnly :: [Int] -> Bool
> > isOneOnly oneOnly = True
> > isOneOnly tester = False
>
> what I want to do is to define a 'type' oneOnly as [1] and use it on
> the pattern matching in function isOneOnly. But it does not work as
> I expect:
>
> When I type
>
> isOneOnly [1]
>
> it will be  True  which is the result I expect but for
>
> is OneOnly [1,2]
>
> the result keeps True, it seems the second pattern has been ignored,
> I think I try to achieve the purpose in a wrong way, any suggestion?

In "isOneOnly oneOnly ", the pattern oneOnly is a variable pattern, it matches 
everything, it also matches [] and _|_. the fact that it is also the name of 
an entity defined elsewhere doesn't matter. You can find more about pattern 
matching (basically, a pattern is a wildcard, a variable or a constructor 
applied to patterns) in the report.
If you turn on warnings for overlapping patterns, GHC will warn you:

$ ghci -fwarn-overlapping-patterns OneOnly
GHCi, version 6.8.3: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( OneOnly.hs, interpreted )

OneOnly.hs:4:0:
    Warning: Pattern match(es) are overlapped
             In the definition of `isOneOnly': isOneOnly tester = ...
Ok, modules loaded: Main.
*Main> isOneOnly undefined
True


Depending on what you want to achieve, maybe 
isOneOnly [1] = True
isOneOnly _ = False

or
isOneOnly [_] = True
isOneOnly _ = False

is the solution.
>
> Thanks and Merry Christmas
>
> Best wishes,
> Raeck
>



More information about the Beginners mailing list