[Haskell-beginners] Looking for more information about Pattern Matching

Sean Perry shaleh at speakeasy.net
Fri Apr 29 02:57:46 CEST 2011


On Apr 28, 2011, at 5:35 PM, Graham Hopper wrote:

> Hi,
> 
> I am very much a newbie to Haskell and currently working through http://learnyouahaskell.com and trying some of the http://www.haskell.org/haskellwiki/99_questions. I am struggling to get my head around pattern matching. I think I can understand the individual patterns presented in LYAH, but can't seem to find any information about generalising the formats. 
> 
> Is there a good resource that describes the patterns that are available or provides more details about how to create them.
> 
> For example the format of [x] and (x:xs) seem very different and I cant quite get a handle on the syntax(?) behind them. I can see how patterns work when shown an example, but wouldn't know how to create one from scratch.
> 
> I hope you can understand what I am trying to say - its a little difficult to explain.

[x] means a list with one element
(x:xs) means give me the head as x and the rest as xs, you only know there is at least one element.

What is happening is Haskell is using the type constructor to create and deconstruct the value for you.

Look also at the example of 'tell' in LYAH's Pattern Matching with Lists and List Comprehensions. He uses (x:[]) as a synonym for [x].

(I put this in sample.hs)
foo [x] = "Just " ++ show x
foo (x:xs) = "Head " ++ show x ++ foo xs
foo [] = ""

bar (Just x) = show x
bar Nothing  = "Nothing"

data Example = Ex1 Int | Ex2 String
  deriving (Show)

examplePlay (Ex1 n) = "An Int " ++ show n
examplePlay (Ex2 s) = "A String " ++ show s

anotherExample = let e = Ex1 5 in
                 putStrLn $ examplePlay e

$ ghci
Prelude> :load sample
 [1 of 1] Compiling Main             ( sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> foo [1..10]
"Head 1Head 2Head 3Head 4Head 5Head 6Head 7Head 8Head 9Just 10"
*Main> foo [1]
"Just 1"
*Main> foo []
""
*Main> bar $ Just 5
"5"
*Main> bar $ Just [1..10]
"[1,2,3,4,5,6,7,8,9,10]"
*Main> bar Nothing
"Nothing"
*Main> examplePlay (Ex1 5)
"An Int 5"
*Main> examplePlay (Ex2 "Foo")
"A String \"Foo\""
*Main> anotherExample
An Int 5


More information about the Beginners mailing list