Skip to content

Instantly share code, notes, and snippets.

@HarryCoops
Last active August 29, 2015 14:24
Show Gist options
  • Save HarryCoops/60c8e981b89ec544ce53 to your computer and use it in GitHub Desktop.
Save HarryCoops/60c8e981b89ec544ce53 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment