Created
October 15, 2019 23:19
-
-
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.
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
| {- | |
| 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