我刚发现
PatternGuards
语言扩展,看起来很不错。
我所处的情况是,我希望模式匹配出一个值,对该值应用一个一元布尔函数,并且只在结果为
False
。否则,我想执行默认操作(可能不像下面列出的那样简单)。
这可以通过使用
if
在进行模式匹配之后,但我宁愿不复制默认操作的代码,或者在单独的函数中删除该代码(即保持防护的穿透行为)
有没有办法做到这一点
没有
这个
如果
?
{-# LANGUAGE GeneralizedNewtypeDeriving, PatternGuards #-}
import Control.Applicative
import Control.Monad.State
newtype MyM a = MyM (StateT Int (Either String) a)
deriving ( MonadState Int
, Monad, Applicative, Functor
)
--------------------------------------------------------------------------------
foo :: Int -> MyM Bool
foo = undefined
bar :: Either a Int -> MyM Int
bar (Right n)
| ok <- foo n, ok == False = return 42
bar _ = return 0
以上代码给出错误消息
Couldn't match expected type âMyM Boolâ with actual type âBoolâ
In the second argument of â(==)â, namely âFalseâ
In the expression: ok == False