How to write this case expression with view template syntax?

After I read an example of an RPN calculator in the section β€œFind out that you have Haskell for great good!” I wanted to rewrite it myself in a more general way.

To easily expand the available functions, I put them in separate lists and a template corresponding to the lookup function using the ViewPatterns syntax. To read input using read , I wrote the following:

 parse xs x = case readMaybe x of Just x -> Right (x : xs) Nothing -> Left "Syntax error 

but I would rather avoid the case expression and use the view template again, for example:

 parse xs (readMaybe -> Just x ) = Right (x : xs) parse xs (readMaybe -> Nothing) = Left "Syntax error" 

However, with the latter, I get this error: No instance for (Read a0) arising from a use of 'readMaybe'

I do not understand why. Aren't they equivalent?

All code is here .

+7
pattern-matching haskell
source share
1 answer

They are not equivalent. The case version has one readMaybe , the presentation template version has two. For each readMaybe compiler must determine what type is the target of the read attempt. When the code says

 parse xs x = case readMaybe x of Just x -> Right (x : xs) Nothing -> Left "Syntax error 

the GHC detective notes that in your case, Just x x ends with xs , and therefore it must accept any type of xs element. And this is a good job.

But when you write

 parse xs (readMaybe -> Just x ) = Right (x : xs) parse xs (readMaybe -> Nothing) = Left "Syntax error" 

you create two separate find-target problems, one for each use of readMaybe . The first of them is solved exactly the same as in the case case , but for the second it is read separately,

 parse xs (readMaybe -> Nothing) = Left "Syntax error" 

there is no idea what it is that you are not reading, and there is no reason to believe that it is the same as in the line above.

It is generally not practical to use presentation templates unless there is only one result of interest. They are the wrong syntax if you want to do an intermediate calculation once, but analyze the result in several cases. I am happy to stay on the record that I believe that they are erroneous for this reason.

+11
source share

All Articles