Skip to content

Instantly share code, notes, and snippets.

@AgtLucas
Forked from animatedlew/patternMatch.hs
Created February 17, 2018 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AgtLucas/befb1b16255e9bfd2a98ce06f6efd753 to your computer and use it in GitHub Desktop.
Save AgtLucas/befb1b16255e9bfd2a98ce06f6efd753 to your computer and use it in GitHub Desktop.
Here are some examples of pattern matching in Haskell.
-- Haskell will match starting at the top, until it hits a catchall
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial(n - 1)
-- Haskell is able to match empty lists and x:xs patterns
head' :: [a] -> a
head' [] = error "No head available on empty lists!"
head' (x:_) = x
-- Here we use a type class to make sure we can convert the input (inner) types to strings
tell :: (Show a) => [a] -> String
tell [] = "Empty"
tell (x:[]) = "Contains only 1 item: " ++ show x
tell (x:y:[]) = "Contains only 2 items: " ++ show x ++ " and " ++ show y
tell all@(x:y:_) = "Contains many items... "++ show all
tell [1, 2, 3, 4]
-- "Contains many items... [1,2,3,4]"
-- Here is a variation on tell using [Char]
tell' :: String -> String
tell' "" = "Empty"
tell' all@(x:xs) = all ++ " -- first letter: " ++ [x] ++ " remaining letters are: " ++ xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment