【问题标题】:Error handling in Haskell with Either monadHaskell 中的错误处理与 Either monad
【发布时间】:2009-06-03 01:04:44
【问题描述】:

我有一个函数可以检查一个类型是否是另一个类型的子类型:

st :: Monad m => Map String Type  -- ^type environment
   -> Set (Type, Type) -- ^assumed subtypes
   -> (Type, Type) -- ^we are checking if lhs <: rhs      
   -> m (Set (Type, Type))

我想做错误处理。我有以下定义:

instance Monad (Either String) where
  return v = Right v
  fail s = Left s
  (Left s) >>= _ = Left s
  (Right v) >>= f = f v

有时我可以通过将 st 的结果视为 Either 来进行错误处理。例如,以下函数有效,并获取我在 st 中调用“失败”所产生的消息:

isSubType env cs t1 t2 = result where
  result = case st env (S.empty) (t1, t2) of
    Left msg -> Left msg
    Right rel -> Right ()

现在,我在 st 里面,我想递归调用它。出于某种原因,以下代码嵌套在 st 深处:

  let do_t1 rel t1 = case st env rel (t1, t2) of
        Left msg -> fail $ printf "type %s in the union is not a subtype\
                           \ of the rhs, %s, because: %s" (renderType t1)
                           (renderType t2) (show msg)
        Right rel -> return rel

不输入检查,但给我以下错误:

 No instance for (Monad (Either t))
      arising from a use of `st'
                   at src/TypedJavaScript/Types.hs:386:24-42
    Possible fix: add an instance declaration for (Monad (Either t))

为什么将 st 的结果视为 Either 在 'st' 之外有效,但在内部无效?如何更改我的代码以使其也能在内部工作?

【问题讨论】:

标签: haskell error-handling type-inference monads


【解决方案1】:

我认为问题在于您调用show msg 应该只使用msg。结果,编译器无法推断出您的意思是Either String;它所知道的是你有Either t,其中满足约束Show t。用msg 替换show msg 应该可以解决它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 2015-12-28
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多