Haskell code showing how pattern matching can make your code cleaner
-- a long function to tell you what your number is or
-- if it's bigger than 5
onetofive :: (Integral a) => a -> String
onetofive x = do
if x == 1 then
"One!"
else
if x == 2 then
"Two!"
else
if x == 3 then
"Three!"
else
if x == 4 then
"Four!"
else
if x == 5 then
"Five!"
else
"A number bigger than five!"
-- a much neater function that does the same thing using pattern matching
onetofivebetter :: (Integral a) => a -> String
onetofivebetter 1 = "One!"
onetofivebetter 2 = "Two!"
onetofivebetter 3 = "Three!"
onetofivebetter 4 = "Four!"
onetofivebetter 5 = "Five!"
onetofivebetter x = "A number bigger than five!"
main = do
print (onetofive 2)
print (onetofive 8)
print ""
-- pattern matching function has same output
print (onetofivebetter 2)
print (onetofivebetter 8)