如果我忽略该值,我可以忽略 Either Right 的类型吗?
Can I ignore the type of Either Right if I'm ignoring the value?
我有一个连续三次运行以下模式的 IO 操作:
runAction :: IO a -> IO Bool
runAction action = do
result <- action
case result of
Right _ -> return True
_ -> return False
callingFunc :: IO Bool
callingFunc = do
resA <- runAction a
resB <- runAction b
resC <- runAction c
return (resA && resB && resC)
a :: IO (Either ByteString Integer)
b :: IO (Either ByteString ByteString)
c :: IO (Either ByteString Bool)
这工作正常,但我想消除一些冗余。由于 Either 右侧的类型,这不起作用:
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Data.ByteString.Char8 as BSC
runAction :: Bool -> IO (Either ByteString a) -> IO Bool
runAction prev action = do
result <- action
case result of
Right _ -> return prev
_ -> return False
actA :: IO (Either ByteString Integer)
actA = return (Right 1)
actB :: IO (Either ByteString Bool)
actB = return (Right True)
main :: IO ()
main = do
res <- foldM runAction True [actA, actB]
print res
产生的错误:
Actions.hs:25:38:
Couldn't match type ‘Bool’ with ‘Integer’
Expected type: IO (Either ByteString Integer)
Actual type: IO (Either ByteString Bool)
In the expression: actB
In the third argument of ‘foldM’, namely ‘[actA, actB]’
但我从来没有真正看过价值。我只是检查我是否正确。
有什么方法可以隐藏或忽略Right of Either的类型吗?有没有更好或更惯用的方法来减少或抽象它?
编辑:抱歉,一定是粘贴了旧的代码副本。已更新。
您的问题来自 actA
和 actB
的类型在同一个列表中。 Haskell 中的列表是同类的,不能混合不同类型的元素。 actA
和 actB
具有明显不同的类型,无法统一类型。你不能有类型 [Either a1 b1, Either a2 b2]
,这种东西根本不存在(无论如何,没有很多扩展和类型系统魔法)。
我有一个连续三次运行以下模式的 IO 操作:
runAction :: IO a -> IO Bool
runAction action = do
result <- action
case result of
Right _ -> return True
_ -> return False
callingFunc :: IO Bool
callingFunc = do
resA <- runAction a
resB <- runAction b
resC <- runAction c
return (resA && resB && resC)
a :: IO (Either ByteString Integer)
b :: IO (Either ByteString ByteString)
c :: IO (Either ByteString Bool)
这工作正常,但我想消除一些冗余。由于 Either 右侧的类型,这不起作用:
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Data.ByteString.Char8 as BSC
runAction :: Bool -> IO (Either ByteString a) -> IO Bool
runAction prev action = do
result <- action
case result of
Right _ -> return prev
_ -> return False
actA :: IO (Either ByteString Integer)
actA = return (Right 1)
actB :: IO (Either ByteString Bool)
actB = return (Right True)
main :: IO ()
main = do
res <- foldM runAction True [actA, actB]
print res
产生的错误:
Actions.hs:25:38:
Couldn't match type ‘Bool’ with ‘Integer’
Expected type: IO (Either ByteString Integer)
Actual type: IO (Either ByteString Bool)
In the expression: actB
In the third argument of ‘foldM’, namely ‘[actA, actB]’
但我从来没有真正看过价值。我只是检查我是否正确。
有什么方法可以隐藏或忽略Right of Either的类型吗?有没有更好或更惯用的方法来减少或抽象它?
编辑:抱歉,一定是粘贴了旧的代码副本。已更新。
您的问题来自 actA
和 actB
的类型在同一个列表中。 Haskell 中的列表是同类的,不能混合不同类型的元素。 actA
和 actB
具有明显不同的类型,无法统一类型。你不能有类型 [Either a1 b1, Either a2 b2]
,这种东西根本不存在(无论如何,没有很多扩展和类型系统魔法)。