Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you apply multiple cases in a replace in Haskell?

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?

like image 696
BrainFRZ Avatar asked Dec 11 '25 04:12

BrainFRZ


1 Answers

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])
like image 93
4castle Avatar answered Dec 14 '25 03:12

4castle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!