2012-04-23 14 views
3

我應該傳遞給「遍歷」(從迭代器模式的本質)的函數,以便我可以基於每個原始元素積累狀態,然後根據原始元素和狀態映射到目前爲止。如何使用遍歷TypeClass根據元素累積狀態,然後映射狀態和元素?

在'collect'和'disperse'中,只有映射取決於狀態,或者狀態取決於元素,但不能同時存在。

http://etorreborre.blogspot.co.uk/2011/06/essence-of-iterator-pattern.html似乎說我應該使用'遍歷',但遍歷是實現所有其他的功能,所以我有點失落。

+1

這與Haskell有什麼關係?我認爲該標籤應該被刪除。 – 2012-04-23 21:52:07

+0

你能舉個例子嗎? – 2012-04-23 21:59:12

+0

聽起來像mapAccumL/mapAccumR。有關Haskell版本,請參閱http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Traversable.html#v:mapAccumL。 (點擊右邊的代碼來看看它是如何實現的)。 – 2012-04-23 22:19:36

回答

5

當您使用traverse方法與函數返回一個State,你會得到你想要什麼:

// a function using the current element and the previous state 
    def function[S, T](s: S, t: T): R = // combine T and S 

    // return a State instance to use as an Applicative with traverse 
    def myState[T, S](t: T) = State[S, R]((s: S) => function(s, t)) 

    // a sequence to traverse 
    val sequence: Seq[T] = ... 

    // use the traverse method 
    sequence.traverse(t => myState(t)) 
0

什麼,我想做一個例子:

main = putStrLn $ show $ runState s 0 
    where 
     s = traverse f [1,2,3,4,5] 
     f = \x -> state(\y -> (x*20+y, y+x)) 

結果([20,41,63,86,110],15)