Skip to content

Instantly share code, notes, and snippets.

@ExC0d3
Created October 15, 2019 23:19
Show Gist options
  • Select an option

  • Save ExC0d3/52c433ae7a63e752bd33a1c3592aded9 to your computer and use it in GitHub Desktop.

Select an option

Save ExC0d3/52c433ae7a63e752bd33a1c3592aded9 to your computer and use it in GitHub Desktop.
A sample script to find words in a string that are of even length and are also palindromes.
{-
Write a function called `evenAndPalindromeStrings`
that takes a string as an input and returns the
words in the string that are of even length and are
also palindromes.
Input - "abba cbbc cbc"
Ouptut - ["abba","cbbc"]
Psuedo code -
1) Break the string by spaces into a list of words
2) For each word -
if it is of even length and is a palindrome
pick it as an answer
NOTE - A string is just a list of chars
-}
-- function to calculate length of a list
len :: [a] -> Int
len [] = 0
len (x:xs) = 1 + len xs
-- function to check if a number is even
isEven :: Int -> Bool
isEven num = num `mod` 2 == 0
-- function to split a string by space
splitBySpace :: String -> [String]
splitBySpace "" = [""]
splitBySpace (x:xs)
| x == ' ' = "" : remaining
| otherwise = (x : head remaining) : tail remaining
where
remaining = splitBySpace xs
-- reverses a given word
reverseString :: String -> String
reverseString "" = ""
reverseString (x : xs) = reverseString xs ++ [x]
-- function to check if a word is palindrome
isPalindrome :: String -> Bool
isPalindrome "" = True
isPalindrome word = word == (reverseString word)
evenAndPalindromeStrings :: String -> [String]
evenAndPalindromeStrings "" = []
evenAndPalindromeStrings string =
[word | word <- wordsInStrings, isPalindrome word, isWordOfEvenLength word]
where
wordsInStrings = splitBySpace string
isWordOfEvenLength word = isEven (len word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment