(many alphaNum <|> many space) <*> char '"' where mstri...">

Haskell parsec parser space analysis errors

I have

stringparse = mstring <$> char '"' <*> (many alphaNum <|> many space) <*> char '"' where mstring abc = [a] ++ b ++ [c] 

When i do this

parse stringparse "" "\"hello\" I get Right "\"hello\""

When i do this

parse stringparse "" "\"\"" I get Right "\"\""

But when I do this,

parse stringparse "" "\" \"" or parse stringparse "" "\"he llo\""

he does not work.

I get errors

 Left (line 1, column 2): unexpected " " expecting letter or digit or "\"" 

and

 Left (line 1, column 4): unexpected " " expecting letter or digit or "\"" 

respectively.

I do not understand why the code does not parse spaces properly.

+4
source share
1 answer

This is because you are doing this many alphaNum <|> many space . many accepts 0 as an acceptable number of characters; it always succeeds. This is the same behavior as * in regular expressions.

So, in <|> it will never work and will call the right side. So you say, "try as much alphaNum as you can, then get it. "

Do you want to

 many (alphaNum <|> space) 

In other words, "as many alphaNum or space as possible."

+10
source

Source: https://habr.com/ru/post/1501971/


All Articles