escapeHTML

escapeHTML を作ってみた。


Prelude> :set editor vi
Prelude> :edit esc.hs
Prelude> :load esc.hs
[1 of 1] Compiling Main ( esc.hs, interpreted )
Ok, modules loaded: Main.
Main> :!cat esc.hs
escapeHTML :: String -> String
escapeHTML cs = concatMap escape cs
where
escape :: Char -> String
escape '&' = "&"
escape '\"' = """
escape '>' = ">"
escape '<' = "&lt;"
escape c = [c]

Main> escapeHTML "aaa,\"bbb\" & <abc>"
"aaa,&quot;bbb&quot; &amp; &lt;abc&gt;"

以下は Prelude のソース。


http://www.haskell.org/ghc/docs/6.10.2/html/libraries/base/Prelude.html

-- | Concatenate a list of lists.
concat :: a -> [a]
concat = foldr (++) []

-- | Map a function over a list and concatenate the results.
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = foldr ((++) . f) []

foldr :: (a -> b -> b) -> b -> [a] -> b
-- foldr _ z [] = z
-- foldr f z (x:xs) = f x (foldr f z xs)
{-# INLINE [0] foldr #-}
-- Inline only in the final stage, after the foldr/cons rule has had a chance
foldr k z xs = go xs
where
go [] = z
go (y:ys) = y `k` go ys