Reputation: 457
i m not familiar with askell.
i have to do this function parseChar :: Char -> Parser Char
> parseChar 'a' " abcd "
Just ('a', "bcd")
> parseChar 'z' " abcd "
Nothing
i did this function
type Parser r = String -> Maybe (Char, String)
parseChar :: Char -> Parser Char
parseChar x = \xs -> Just(x, xs)
i dont really understand the \ and how can I take all the string except the second.
Thanks!!
Upvotes: 1
Views: 1324
Reputation: 476503
i dont really understand the
\
and how can I take all the string except the second.
The \
is a lambda expression \xs -> …
is a function that maps a variable xs
to the …
part. Here you can however move the variable to the head of the clause.
You however need to check if the first element of the string is indeed the element you are parsing:
parseChar :: Char -> Parser Char
parseChar _ "" = Nothing
parseChar x (y:ys)
| x == y = Just (y, ys)
| otherwise = Nothing
Here x
is thus the char we want to parse, and ""
or (y:ys)
the string that we are parsing. ""
means that the string is empty, in which case we return Nothing
. If the string is not empty, we unpack it in the first character (head) y
, and the list of remaining characters (tail) ys
. In case x == y
, we are thus parsing the correct character, and we can return a 2-tuple wrapped in a Just
constructor. In case x
is not equal to y
, the parser should "fail" and return Nothing
.
This then yields:
Prelude> parseChar 'a' "abcd"
Just ('a',"bcd")
Prelude> parseChar 'z' "abcd"
Nothing
Prelude> parseChar 'a' ""
Nothing
Upvotes: 3