haskell - 如何将失败的计算转换为成功的计算,反之亦然

标签 haskell typeclass alternative-functor monadplus

这很可能是一个寻求问题的解决方案......如果是这样,我请求你的宽容!

可能的实现:

class Switch' f where
  switch :: f a -> f ()

instance Switch' [] where
  switch []     = [()]
  switch (_:_)  = []

instance Switch' Maybe where
  switch Nothing   = Just ()
  switch (Just _)  = Nothing

解释是:给定一个成功的计算,让它失败;给定一个失败的计算,让它成功。我不确定,但这似乎与 MonadPlus 正好相反……如果你眯着眼睛真的很用力的话。 ???

这个概念是否有标准类型类或其他实现?如果有的话,底层数学会是什么样子(即这是一个半群、一个循环等)?

最佳答案

switch :: (Alternative f, Eq (f a)) => f a -> f ()
switch x | x == empty = pure ()
         | otherwise = empty

或者
switch :: (MonadPlus m, Eq (m a)) => m a -> m ()
switch x | x == mzero = return ()
         | otherwise = mzero

关于haskell - 如何将失败的计算转换为成功的计算,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146980/

相关文章:

haskell - Applicative 是否有翻转运算符?

haskell - Haskell : Graham Hutton Book-(old-Yellow), Parsing (Ch-8)

haskell - 在 Haskell 中,Ord 和 Enum 有时不兼容吗?

haskell - Monad 是替代品但不是 MonadPlus 的例子是什么?

haskell - 如何使用Shake执行sh命令

list - 证明流的平等

typeclass - 是否存在 Show Int 类型的值?

haskell - 为什么使用具有重叠实例的类型类的此函数在 GHCi 中表现不同?

用于条件/替代的推测执行的 Haskell 策略