Design Pattern Matching

I recently encountered an error when using threepenny-gui , and this was resolved by changing the code from the pattern match in the <- to match the pattern with let.

Are there any reasons why I should expect a change in behavior when changing between these two forms of pattern matching?

In particular, the following code:

In monad IO:

 Just events <- Map.lookup elid <$> readMVar sElementEvents 

has been changed to:

 mevents <- Map.lookup elid <$> readMVar sElementEvents let Just events = mevents 

Here is the fix fix fix link for me: https://github.com/Davorak/threepenny-gui/commit/fbf6cbe25875fafdc64f7a111ddebf485b45143b

Additional platform information: os: 10.8.5 ghc: 7.6.3

edit: added that this happens in IO monad

+6
source share
1 answer

Actually, yes, they give rise to various errors. The lack of conformity to the pattern in the let binding causes a match to the error pattern whenever this match is evaluated if there is no match to the pattern from (<-) , just calls the Monad instance fail function

As a simple example, consider the Maybe monad where

 instance Monad Maybe where ... fail _ = Nothing test1 :: Maybe (Maybe ()) test1 = do Just a <- return Nothing return a test2 :: Maybe (Maybe ()) test2 = do ma <- return Nothing let Just a = ma return a 

If we call them both, we get completely different behavior

 > test1 Nothing > test2 Just *** Exception: PM.hs:23:7-17: Irrefutable pattern failed for pattern Data.Maybe.Just a 

In the general case, an irrefutable match is a bad idea if you are really not sure about the impossibility of getting the missing templates, but if you have to do it in Monad , then sometimes an irrefutable match on a binding is better than let .

+9
source

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


All Articles