我有这种格式的计算:s -> a -> s,其中s是某种状态的类型。这种函数的结果也是下一次评估的状态。例如,
appendInt :: String -> Int -> String
appendInt s i = s ++ (show i)然后,appendInt "Int: " 1会给"Int: 1",而(appendInt $ appendInt "Int: 1") 2会给"Int: 12"。然而,我无法找到一种方法将这种计算放在State Monad中。
首先猜测是s -> (s,s),但a不能传入。然后,我尝试了(a -> s) -> (s, a -> s),但是没有a也不可能获得s。s -> (a,s)不能工作,因为a是输入而不是输出。
那么,我应该如何包装这个计算呢?State monad是否适合这样做?
发布于 2015-10-08 07:16:49
您可以很好地使用State,或者更好地使用Writer。
import Control.Monad.Writer
import Control.Monad.State
appendInt :: Int -> Writer String ()
appendInt i = tell $ show i
appendInt' :: Int -> State String ()
appendInt' i = modify (++ show i)
main = do print . execWriter $ do
tell "Int: "
appendInt 1
appendInt 2
print . flip execState "Int: " $ do
appendInt' 1
appendInt' 2https://stackoverflow.com/questions/33007560
复制相似问题