我想做的是从 Reader monad 中创建一个 Applicative Functor,它执行以下操作:
data MyData = Int Int
get2Sum :: Reader [Int] Int
get2Sum = do
myData <- ask
let fst2 = take 2 myData
case length fst2 of
2 -> return $ sum fst2
_ -> return 0
myDataFromApplicative = MyData <$> get2Sum <*> get2Sum
main = print $ runReader myDataFromApplicative [1,2]
但是,如果运行类似
runReader myDataFromApplicative [1]
而不是给我MyData 0 0
我要它给我Error
我正在尝试创建自己的 Reader Monad 来完成此操作,但无法完全弄清楚。
我想象的是这样的(显然这只是一个大纲
data SuccessReader r a = Interm {runSuccessReader :: r -> SuccessReader a} | Success a | Error
throwError :: SuccessReader ()
get2Sum :: Reader [Int] Int
get2Sum = do
myData <- ask
let fst2 = take 2 myData
case length fst2 of
2 -> return $ sum fst2
_ -> throwError
myDataFromApplicative = MyData <$> get2Sum <*> get2Sum
main = do
print $ runSuccessReader myDataFromApplicative [1,2]
print $ runSuccessReader myDataFromApplicative [1]
这将输出
Success MyData 3 3
Error