What I would like to do is make an applicative Functor from the Reader monad, which does something like this:
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]
However, if you run something like
runReader myDataFromApplicative [1]
Instead of giving me MyData 0 0
I want him to give me Error
I played with creating my own Reader Monad to achieve this, but couldn't figure it out.
I think this is something like this (obviously this is just a circuit
data SuccessReader ra = 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]
which outputs
Success MyData 3 3 Error
source share