Reputation: 191
I'm trying to write a parser in Haskell.
This parser take a string (example: "abc def") in parameter and return a Maybe (String, String).
Maybe (String, String)
First String get characters while it's number or letter.
Second String get the rest
In this example, I want to return Maybe ("abc", " def").
parseString :: String -> Maybe (String, String)
parseString "" = Nothing
parseString expr = case isString expr of
Just (char, rest) -> fmap (char:) (parseString rest)
Nothing -> Just ("", expr)
isString return :
Maybe (Char, String) -> Char = first character, String = rest / Nothing if isn't a letter or digit.
The problem, I can not return the rest of my String in the maybe.
Upvotes: 1
Views: 629
Reputation: 116139
The issue seems to be in
fmap (char:) (parseString rest)
Now, (char:)
is a function String -> String
, so fmap (char:)
becomes Maybe String -> Maybe String
(or its generalization to another functor). However, parseString rest
is not a Maybe String
, it is a Maybe (String, String)
.
So, we need to adapt (char:)
to work on the first component of that pair. I'd try
fmap (\(res,rest2) -> (char:res, rest2)) (parseString rest)
(By importing first
from Data.Bifunctor
or Control.Arrow
, that can be written as fmap (first (char:)) (parseString rest)
, but that's not that important.)
Upvotes: 2