Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module BeginningHaskellTalkExamples where
isPalindromeWithRecursion :: String -> Bool
isPalindromeWithRecursion str =
loop strEndIndex where
strEndIndex = length str - 1
loop i =
if (i <= (div strEndIndex 2)) then True
else if (str !! i) /= str !! (strEndIndex - i) then False
else loop (i - 1)
isPalindromeWithRecursionAndGuard :: (Eq a) => [a] -> Bool
isPalindromeWithRecursionAndGuard str =
loop strEndIndex where
strEndIndex = length str - 1
loop i
| i <= (div strEndIndex 2) = True
| (str !! i) /= str !! (strEndIndex - i) = False
| otherwise = loop (i - 1)
isPalindromeWithRecursionAndPatternMatch :: String -> Bool
isPalindromeWithRecursionAndPatternMatch str =
case str of
[] -> True
x : [] -> True
x1 : x2 : [] -> x1 == x2
x1 : xs -> x1 == last xs && isPalindromeWithRecursionAndPatternMatch (init xs)
--data Book =
-- Single String
-- | Trilogy String
-- | Series String
-- deriving (Show)
data Book =
Single { title :: String }
| Trilogy { title :: String }
| Series { title :: String }
deriving (Show)
b = Single { title = "hello"}
instance Eq Book where
(==) (Single t1) (Single t2) = t1 == t2
(==) (Trilogy t1) (Trilogy t2) = t1 == t2
(==) (Series t1) (Series t2) = t1 == t2
(==) _ _ = False
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome (x : []) = True
isPalindrome (x1 : x2 : []) = x1 == x2
isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs)
areAllPalindromesWithRecursion :: (Eq a) => [[a]] -> Bool
areAllPalindromesWithRecursion listOfLists =
loop listOfLists where
loop lOfl =
case lOfl of
[] -> True
(x : xs) -> isPalindrome x && loop xs
areAllPalindromesWithRefinedRecursion :: (Eq a) => [[a]] -> Bool
areAllPalindromesWithRefinedRecursion [] = True
areAllPalindromesWithRefinedRecursion (x : xs) = isPalindrome x && areAllPalindromesWithRefinedRecursion xs
areAllPalindromesWithFoldR :: (Eq a) => [[a]] -> Bool
areAllPalindromesWithFoldR lOfLs =
foldr (\x result -> isPalindrome x && result) True lOfLs
areAllPalindromesWithMapFoldComposed :: (Eq a) => [[a]] -> Bool
areAllPalindromesWithMapFoldComposed = foldr (&&) True . map isPalindrome
onlyPalindromes :: (Eq a) => [[a]] -> [[a]]
onlyPalindromes = filter isPalindrome
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment