简体   繁体   中英

Haskell Parsing Recursion and Maybe

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM