squish
is an onomatopoeic string function provided by Ruby on Rails that works on strings.
Given a string, squish
condenses all the consecutive spaces into one.1 (Imagine that you take a string at both ends and compress it with both hands, spaces will be merged and you will hear the typical squish
sound).
I went I little overboard and wrote three variations of this function:
squishAll
that will squish together all repeated chars:squishAll "aaabbbccc" -> "abc"
squishOn
that will squish together any specified char:squishOn 'a' "aaabbbccc" -> "abbbccc"
squish
for spaces only:squish "foo bar baz" -> "foo bar baz"
import Data.List
import Data.Foldable
squishAll :: Eq a => [a] -> [a]
squishAll = (map head) . group
squishOn :: Eq a => a -> [a] -> [a]
squishOn item = Data.List.concat . (map firstIfEqualElseAll) . group
where firstIfEqualElseAll (x:xs) = if x == item then [x] else (x:xs)
squish = squishOn ' '
main = print $ [squishAll "aaabbbccc", squishOn 'a' "aaabbbccc", squish "foo bar baz"]
1 The Ruby function that this is modelled on would also remove any spaces at the start and at the end. I've chosen not to implement this.