1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

What is char: if I may? I do not understand the colon.
@Evgeny (expression symbol) is a section, a shorthand for (\x -> expression symbol x), so (char:) means (\x -> char : x), the function which prepends char to the input string x.
Oh, the : is from list contructor, a kind of point free prepending at head of list? Thanks for explaining to me, @chi, it looked like a mystery.
@Evgeny Yes, it is one of the list constructors (the other one being [] for the empty list).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.