Haskell Monad状态示例

时间:2019-02-09 04:33:28

标签: haskell state-monad

我正在尝试通过重复遍历字符串或整数列表,对它们进行计数,然后用整数Control.Monad.State替换字符串条目,来测试Haskell的0。我已经成功完成了计数工作,但是创建替换列表失败。这是我的代码 正确地将[3,6]打印到屏幕上。如何使其创建所需的列表[6,0,3,8,0,2,9,1,0]

module Main( main ) where

import Control.Monad.State

l = [
    Right 6,
    Left "AAA",
    Right 3,
    Right 8,
    Left "CCC",
    Right 2,
    Right 9,
    Right 1,
    Left "D"]

scanList :: [ Either String Int ] -> State (Int,Int) [ Int ]
scanList [    ] = do
    (ns,ni) <- get
    return (ns:[ni])
scanList (x:xs) = do
    (ns,ni) <- get
    case x of
        Left  _ -> put (ns+1,ni)
        Right _ -> put (ns,ni+1)
    case x of
        Left  _ -> scanList xs -- [0] ++ scanList xs not working ...
        Right i -> scanList xs -- [i] ++ scanList xs not working ...

startState = (0,0)

main = do
    print $ evalState (scanList l) startState

1 个答案:

答案 0 :(得分:5)

[0] ++ scanList xs不起作用,因为scanList xs不是列表,而是State (Int,Int) [Int]。要解决此问题,您将需要使用fmap / <$>

您还需要更改基本大小写,以不使状态值成为返回值。

scanList :: [Either String Int] -> State (Int, Int) [Int]
scanList []     = return []
scanList (x:xs) = do
    (ns,ni) <- get
    case x of
        Left  _ -> put (ns+1, ni)
        Right _ -> put (ns, ni+1)
    case x of
        Left  _ -> (0 :) <$> scanList xs
        Right i -> (i :) <$> scanList xs

但是,为了进一步简化代码,最好使用mapM / traversestate来删除大部分递归模板和get / put语法。

scanList :: [Either String Int] -> State (Int, Int) [Int]
scanList = mapM $ \x -> state $ \(ns, ni) -> case x of
    Left  _ -> (0, (ns+1, ni))
    Right i -> (i, (ns, ni+1))