Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell parsec space parsing errors

Tags:

haskell

parsec

I have

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

When I do,

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

When I do,

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

But when I do,

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

it 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 don't understand why the code does not parse spaces properly.

like image 992
Jay Avatar asked Dec 25 '22 20:12

Jay


1 Answers

It's because you're doing this many alphaNum <|> many space. many accepts 0 as an acceptable amount of characters, it always succeeds. This is the same behavior as * in regexs.

So in a <|> it's never going to fail and call the right side. So you're saying "try as many alphaNum as possible then take a ".

What you want is

many (alphaNum <|> space) 

In other words, "as many alphaNums or spaces as possible".

like image 106
Daniel Gratzer Avatar answered Jan 12 '23 05:01

Daniel Gratzer