Skip to content

Instantly share code, notes, and snippets.

@gabebw
Created July 31, 2015 23:45
Show Gist options
  • Save gabebw/a837caca1869ab4daafa to your computer and use it in GitHub Desktop.
Save gabebw/a837caca1869ab4daafa to your computer and use it in GitHub Desktop.
module PatternMatching where
-- Return the first character of a String, or the question mark character for an
-- empty string.
-- > firstCharacter "hello"
-- 'h'
-- > firstCharacter ""
-- '?'
-- Hint: String is the same as [Char].
firstCharacter :: String -> Char
firstCharacter (c:_) = c
firstCharacter _ = '?'
-- Move the first character to the end of a String and add "ay." It's Pig Latin!
-- > pigLatin "hello"
-- "ellohay"
-- Watch out for empty strings!
pigLatin :: String -> String
pigLatin (c:cs) = cs ++ [c] ++ "ay"
pigLatin "" = ""
-- Return True if both items in the tuple are True.
-- > bothTrue (True, True)
-- True
-- > bothTrue (True, False)
-- False
bothTrue :: (Bool, Bool) -> Bool
bothTrue (a, b) = a && b
-- Return True for a character containing an odd digit, and False for any other
-- character.
-- > isOddDigit '3'
-- True
-- > isOddDigit '2'
-- False
-- > isOddDigit 'q'
-- False
isOddDigit :: Char -> Bool
isOddDigit '1' = True
isOddDigit '3' = True
isOddDigit '5' = True
isOddDigit '7' = True
isOddDigit '9' = True
isOddDigit _ = False
-- Return a new list where the first item is duplicated.
-- > duplicated [1, 2, 3]
-- [1, 1, 2, 3]
-- Watch out for empty lists!
-- Hint: try to avoid any repetition in your definition.
duplicateFirst :: [a] -> [a]
duplicateFirst l@(x:_) = x:l
duplicateFirst l = l
-- Implement if/then/else as a function!
-- Return the first value if the boolean is true, and the second value if the
-- boolean is false.
-- > ifThenElse "was true" "was false" True
-- "was true"
-- > ifThenElse "was true" "was false" False
-- "was false"
ifThenElse :: a -> a -> Bool -> a
ifThenElse v1 _ True = v1
ifThenElse _ v2 False = v2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment