I'm trying to understand this function (taken from here)
escape :: String -> String
escape =
let
escapeChar c =
case c of
'<' -> "<"
'>' -> ">"
_ -> [c]
in
concat . map escapeChar
My questions are:
escape
is a function that takes a String
. But it seems that in in the fuction definition it does not receive any argument. How does this work?escapeChar
and c
? How is that relationship established? Does c
coming right after escapeChar
have a meaning?Would it be easier if escapeChar
were a top-level definition using pattern matching:
escape :: String -> String
escape = concatMap escapeChar
escapeChar :: Char -> String
escapeChar '<' = "<"
escapeChar '>' = ">"
escapeChar ch = [ch]
[ch]
is a singleton list, it turns ch :: Char
into a [ch] :: String
.
In Haskell you can remove/add an argument from/to each side (eta conversion). escape
is the eta reduced form of
escape :: String -> String
escape str = concatMap escapeChar str
Just like, if you wanted to define a synonym for (+)
you have equivalent ways of writing it. I feel like the add = (+)
is clearest, you are identifying the two functions. The arguments are the same on both sides so we don't specify them.
add :: Int -> Int -> Int
add = (+)
add a = (+) a
add a = (a +)
add a b = (+) a b
add a b = a + b
These are equivalent ways of writing escape
:
escape = concat . map escapeChar
escape str = concat (map escapeChar str)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments