模式匹配为可选的空白或适用的纯字符

问题描述 投票:1回答:1

我知道有可能像这样对(命名的)构造函数进行模式匹配:

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]-&...

haskell typeclass
1个回答
0
投票

您能做的最好的事情是:

© www.soinside.com 2019 - 2024. All rights reserved.