Last active
February 4, 2023 12:32
-
-
Save animatedlew/8120509 to your computer and use it in GitHub Desktop.
Here are some examples of pattern matching in Haskell.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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