【问题标题】:How to use the traverse TypeClass to accumulate state based on the elements and then map over the state and elements?如何使用 traverse TypeClass 根据元素累积状态,然后映射状态和元素?
【发布时间】:2012-04-23 21:45:56
【问题描述】:

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

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

http://etorreborre.blogspot.co.uk/2011/06/essence-of-iterator-pattern.html 的表格似乎说我应该使用 'traverse' 但 traverse 是实现所有其他功能的函数,所以我有点迷茫。

【问题讨论】:

  • 这和 Haskell 有什么关系?我认为应该删除该标签。
  • 你能举个例子吗?
  • 听起来像 mapAccumL/mapAccumR。有关 Haskell 版本,请参阅 hackage.haskell.org/packages/archive/base/latest/doc/html/…。 (点击右边的source看看它是如何实现的。)
  • 好吧,我可以做我想做的事,只需要传递一个返回 State Monad 的函数给 traverse 函数,只是在构造状态时选择合适的函数的问题。好吧,除了实现 Traverse Typeclass 的 haskell 和 scala(z) 之外,我不知道其他语言,这就是我把它放在那里的原因,原始论文也是用 haskell 编写的,我假设使用 haskell 的人很可能熟悉这个 TypeClass。

标签: scala functional-programming iterator


【解决方案1】:

当您将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))

【讨论】:

    【解决方案2】:

    我想做的一个例子:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 2022-06-27
      相关资源
      最近更新 更多