Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Last active February 4, 2023 12:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save animatedlew/8120509 to your computer and use it in GitHub Desktop.
Save animatedlew/8120509 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