我知道有可能像这样对(命名的)构造函数进行模式匹配:
f1 :: Maybe a -> Bool
f1 Nothing = False
f1 (Just x) = True -- in reality have something that uses x here
f2 :: [a] -> Int
f2 [] = False
f2 x = True
我如何为类似于[]的一般Alternative
编写这样的函数>
f :: (Alternative m) => m a -> Bool f empty = False f x = True
如果尝试此操作,则会出现错误
Parse error in pattern: empty
。我想这很有意义,因为empty
在这里是函数而不是构造函数。但是我该如何惯用Alternative
来完成此操作?
编辑1:
我的实际目标是为自定义结果类型定义一个Monad
实例(也可能是一个MonadPlus
实例)。代替基本的Either Error Result
类型,它应该支持Maybe Error
(并且如果可能的话,还支持其他Alternative
,例如[Error]
)作为错误类型,并且还支持某些Applicative
作为结果类型,以支持惰性求值。 我想要类似的东西
instance (Alterantive mErr, Applicative mRes) => Monad (mErr e, mRes a) where
return x = (empty, pure x)
(empty, pure x) >>= f = f x
(err, x) >>= f = (err, x)
我知道有可能像这样对(命名的)构造函数进行模式匹配:f1 ::也许是-> Bool f1 Nothing = False f1(Just x)= True-实际上有些东西在这里使用x x f2: :[a]-&...
您能做的最好的事情是: