I wrote a function to be able to clean word numbers for processing in Haskell. It needs to be able to change - into spaces (i.e. forty-five becomes forty five) and delete every other non-letter. I can define it recursively, but I'd really like to do something cleaner.
clean :: String -> String
clean "" = ""
clean ('-':cs) = ' ' : clean cs
clean (c:cs)
| isLetter c = c : clean cs
| otherwise = clean cs
This led me to defining a custom filter and defining a replace from Data.List.Split based on a comment to this answer, since I'm already using Data.List.Split.
clean :: String -> String
clean = filter (\c -> isLetter c || c == ' ') . replace "-" " " . filter (/= ' ')
where
replace :: String -> String -> String -> String
replace old new = intercalate new . splitOn old
This version is even messier as a whole. Also, this version doesn't remove spaces in the original string. Is a different convention or something built-in that would allow me to do this with use a clean one-liner?
One of the most powerful functions for dealing with lists is concatMap (a.k.a. >>=). You can write your clean function like so:
clean :: String -> String
clean = concatMap (\c -> if c == '-' then " " else [c | isLetter c])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With