D idsea J
D idsea J

Reputation: 113

Append to String if some function is true

I would like to create a function that Prints out every Palindrome from a given List as a List itself.

isPalindrome :: String -> Bool
isPalindrome w = w == reverse w

somefunction :: String -> String
somefunction input = if isPalindrome (input) == True then input else ""

printPalindromes xs = map somefunction (xs)

Almost does the job but if we try

*Main> printPalindromes ["anna","peter","aa","bb","cc","efg"]
              result -> ["anna","","aa","bb","cc",""]

what we would actually like as result is this: result -> ["anna","aa","bb","cc"]

As you can see the function somefunction just returns "" if the given input is not a palindrome. How do I actually do nothing during the else case in somefunction?

Is there a more nice and more compact way to reach my goal?

Upvotes: 2

Views: 110

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

You filter the list, and remove all the elements that are empty lists. You can use the null :: [a] -> Bool function for that:

filterPalindromes :: [String] -> [String]
filterPalindromes = filter (not . null) . map somefunction

It however might make more sense to here use your isPalindrom function directly, especially since if the input is the empty string, then this is a palindrome:

filterPalindromes :: [String] -> [String]
filterPalindromes = filter isPalindrome

Upvotes: 7

Related Questions