14 October, 2013

list monad character to html entity encoding

This isn't particularly fancy, but it struck me as interesting from the "trying to abstract more" perspective.

Given a string with some funny characters in them, change the characters into HTML entities.

Here's a puffing-out function that given a character c :: Char returns a string (a list of characters, [Char]) for it to be replaced with. In the default case, the returned list contains only the original character.

generalPuffer c = case c of 
  c | ord c == 163 -> "£"
  c | ord c == 174 -> "®"
  c | ord c == 153 -> "™"
  c | ord c == 188 -> "¼"
  c | ord c > 128 -> error $ "unknown high character code " ++ (show $ ord c) ++ " encountered."
  c -> [c]

So how to use this? concatMap will handle this, and that was my first implementation (after fusing map and concat in my head).

concatMap f "£1 Shop™"
but concatMap is monadic bind, restricted to the list monad...

So equivalently you could write:

"£1 Shop™" >>= f
or
f =<< "£1 Shop™"
or
 do { l <- "£1 Shop™" ; c l }

No comments:

Post a Comment