haskell - 在返回不同类型的函数中对 monad 进行标记

标签 haskell monads option-type

有没有办法在返回类型不是所述 monad 的函数中为 monad 编写 do 符号?

我有一个主要功能来处理代码的大部分逻辑,并辅以另一个在中间为它进行一些计算的功能。补充函数可能会失败,这就是它返回 Maybe 值的原因。我希望对 main 函数中的返回值使用 do 表示法。举一个通用的例子:

-- does some computation to two Ints which might fail
compute :: Int -> Int -> Maybe Int

-- actual logic 
main :: Int -> Int -> Int
main x y = do
  first <- compute x y
  second <- compute (x+2) (y+2)
  third <- compute (x+4) (y+4)
  -- does some Int calculation to first, second and third

我打算让 firstsecondthird 具有实际的 Int 值,取在 Maybe 上下文之外,但是按照上面的方式进行操作会使 Haskell 提示无法将 Maybe Int 的类型与 Int 匹配。

有没有办法做到这一点?还是我走错方向了?

请原谅我是否错误地使用了某些术语,我是 Haskell 的新手,并且仍在努力了解所有内容。

编辑

main 必须返回一个 Int,而不是包裹在 Maybe 中,因为代码的另一部分使用了 main作为 Int。单个 compute 的结果可能会失败,但它们应该在 main 中共同通过(即至少有一个会通过),而我正在寻找的是一种方法使用 do 符号将它们从 Maybe 中取出,对它们进行一些简单的 Int 计算(例如可能处理任何 Nothing0 形式返回),并以 Int 形式返回最终值。

最佳答案

签名本质上是错误的。结果应该是一个 Maybe Int:

main :: Int -> Int -> <b>Maybe Int</b>
main x y = do
  first <- compute x y
  second <- compute (x+2) (y+2)
  third <- compute (x+4) (y+4)
  <b>return</b> (first + second + third)

例如,这里我们return (first + second + third)return 将把它们包装在Just 数据构造函数中。

这是因为您的 do block 隐式使用了 Monad Maybe>>=,其定义为:

instance Monad Maybe where
    Nothing >>=_ = Nothing
    (Just x) >>= f = f x
    return = Just

所以这意味着它确实会从 Just 数据构造函数中“解压”值,但是如果 Nothing 从中产生,那么这意味着整个 do block 的结果将是 Nothing

这或多或少是 Monad Maybe 提供的便利:您可以将计算作为一系列成功 操作,如果其中一个失败,结果将是 Nothing,否则它将是 Just result

因此,您不能在最后返回一个 Int 而不是 Maybe Int,因为从类型的角度来看,一个或多个绝对有可能计算可以返回Nothing

但是,您可以“发布”处理 do block 的结果,例如,如果您添加一个“默认”值,该值将在其中一个计算为 Nothing< 时使用,例如:

import Data.Maybe(fromMaybe)

main :: Int -> Int -> <b>Int</b>
main x y = <b>fromMaybe 0</b> $ do
  first <- compute x y
  second <- compute (x+2) (y+2)
  third <- compute (x+4) (y+4)
  return (first + second + third)

如果 do block 因此返回 Nothing,我们将其替换为 0(您当然可以在中添加另一个值fromMaybe :: a -> Maybe a -> a 作为值以防计算“失败”)。

如果你想返回 Maybe 列表中的第一个元素 Just,那么你可以使用 asum :: (Foldable t, Alternative f) => t (f a) -> f a , 那么你可以这样写你的 main:

-- first <i>non</i>-failing computation

import Data.Foldable(asum)
import Data.Maybe(fromMaybe)

main :: Int -> Int -> Int
main x y = fromMaybe 0 $ <b>asum</b> [
    compute x y
    compute (x+2) (y+2)
    compute (x+4) (y+4)
]

请注意,asum 仍然可以仅包含 Nothing,因此您仍然需要进行一些后处理。

关于haskell - 在返回不同类型的函数中对 monad 进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795360/

相关文章:

typescript - 递归函数的类型

math - 为什么 Functor 类没有返回函数?

haskell - 为什么询问从 Reader monad 检索环境

swift - 和有什么不一样?和 ? = 无

haskell - 用否定理解函数组合

haskell:在 haskell 平台 2013 2.0.0 中使用 writer monad 时,没有 (Monoid Int) 的实例

haskell - 如何创建一个包含可变向量的类型?

haskell - 处理 GHC 中较高级别类型的特殊情况?

java - 可选的映射类型转换为子类对象

rust - 在 Rust 中处理多个 `Option<T>` 的惯用方法是什么?