Matching Patterns for Equality

parserChar :: Char -> Parser Char parserChar c = Parser ch where ch d = case dvChar d of Parsed c dp -> Parsed c dp _ -> NoParse 

The above function should take Char c and return a parser that will match only c . The dvChar d function will return either a Parsed char dp or NoParse (where char is the next character in the string). So I was hoping that Parsed c dp would only match the result in which char==c , but in fact it happens that the parser returned by this function matches any character (although c seems to be bound to a specific Char, as an argument to a function).

The following function works correctly:

 parserChar :: Char -> Parser Char parserChar c = Parser ch where ch d = case dvChar d of Parsed char dp -> if char == c then Parsed char dp else NoParse _ -> NoParse 

Manual analyzer coding for parsing the letter 'a' also works correctly, in that

 case dvChar d of Parsed 'a' dp -> Parsed 'a' dp _ -> NoParse 

returns the result only if the character was 'a' .

So what gives? Can you only match literals in a similar pattern (for example, despite the fact that Char is in the Eq class, if char==c (..) still needs to be encoded manually), or am I doing something wrong?

+4
source share
1 answer

Yes, you can only answer literals. In fact, the best way to think about this is that you can only match constructors, and it happens that Int, Char, String, and co. all have constructor literals.

Please note that you can also combine the case and protective devices and record it as (from memory):

 parserChar :: Char -> Parser Char parserChar c = Parser ch where ch d = case dvChar d of Parsed char dp | char == c -> Parsed char dp _ -> NoParse 
+7
source

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


All Articles