Understanding bracket use in Haskell – Parser that depends on previous parser gives error when using brackets

  Kiến thức lập trình

Ok so I’m trying to learn Haskell.

This is my Parser.

import Data.Char
data Parser a = MkParser (String -> Maybe (String, a))

This is a parser which parses a string once, and depending on what it parses, it runs another parser.

-- second parse depends on the first
(<<<=) :: Parser a -> (a -> Parser b) -> Parser b
-- a parse, gives Nothing | Just (string, ans depending on a)
(MkParser pa) <<<= k = MkParser sf
    where
        sf inp = case pa inp of
            Nothing -> Nothing
            Just (cs, c) -> unParser (k c) cs

unParser :: Parser a -> String -> Maybe (String, a)
-- applies a parser manually
unParser (MkParser pa) inp = pa inp

Now I use it here (isDigit just checks if the character is a digit, and isAlpha checks if it’s a letter). I also use this basic parser (parses if character is what I am looking for)

char :: Char -> Parser Char
char wanted = MkParser sf
  where
    sf (c:cs) | c == wanted = Just (cs, c)
    sf _ = Nothing

Now when I do this:

t = satisfy isAlpha <<<= x -> satisfy isDigit <<<= y -> char x

it works!

But the moment I put brackets around this

t = satisfy isAlpha <<<= (x -> satisfy isDigit) <<<= y -> char x

it gives an error saying variable x is not in scope… Why?

I initially just placed the brackets because it is easier to read. But turns out my code only works when I remove the brackets.

I tried working with it and realized this works too:

t = satisfy isAlpha <<<= (x -> satisfy isDigit <<<= y -> char x)

Question 1) But why? If it does (x -> satisfy isDigit <<<= y -> char x) first, it wouldn’t know what x is, so how does it work?

Question 2) What’s the evaluation order if I don’t use brackets?

Question 3) And why does it not work when I do (x -> satisfy isDigit)?

All questions are related, and I’m sure I am just misunderstanding the evaluation order. I used to program in OOP languages and I feel like I’m misunderstanding the brackets and evaluation order in Haskell?

New contributor

user20102550 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT