3

我应该传递给“遍历”的函数是什么(从迭代器模式的本质出发),这样我就可以根据每个原始元素累积状态,然后根据原始元素和迄今为止的状态进行映射。

在“收集”和“分散”中,只有映射取决于状态或状态取决于元素,但不能同时取决于两者。

http://etorreborre.blogspot.co.uk/2011/06/essence-of-iterator-pattern.html上的表格似乎说我应该使用“遍历”,但遍历是实现所有其他函数的函数,所以我有点失落。

4

2 回答 2

5

当您将该traverse方法与返回 a 的函数一起使用时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))
于 2012-04-23T23:35:13.367 回答
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)

于 2012-04-24T09:30:52.557 回答