使用 monad 计算对列表上的累积和(haskell)
我有一个对结构列表 [("oct",1),("nov",1),("dec",1)]
我想计算对内的总和: [("十月",1),("十一月",2),("十二月",3)]
。我认为这是单子实现的一个很好的例子,但无法弄清楚如何保存容器。
我尝试在列表上创建函数(我已经了解 scanl1
,只是在这里展示了努力:)
csm (x:[]) = [x]
csm (x:y:xs) = x : csm ((x + y) : xs)
然后尝试类似的操作:
sumOnPairs l = do
pair <- l
return (csm (snd pair))
我的解决方案不起作用,请为我指出正确的方向
I have a list of pairs structure [("oct",1),("nov",1),("dec",1)]
I want to calculate sum within pairs: [("oct",1),("nov",2),("dec",3)]
. I think this is a good case for monadic implementation, but can't figure out how to preserve containers.
I tried to make function on lists (I already know about scanl1
, just showing effort here :)
csm (x:[]) = [x]
csm (x:y:xs) = x : csm ((x + y) : xs)
And then try something like:
sumOnPairs l = do
pair <- l
return (csm (snd pair))
My solution is not working, please point me in the right direction
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
列表 monad 建模了非确定性:对列表中的每个元素执行相同的操作,然后将结果收集到新列表中。
对于您想要的顺序遍历类型(对元素执行某些操作,然后使用结果对下一个元素执行某些操作,等等),您可以使用
State
monad在每个步骤 执行类似的操作,新状态是当月和总和
旧状态的数量和当前状态的数量。
遍历
累加遍历原始列表时列表中的那些状态。
您还可以仅保留状态中的总和,而不是刚刚替换的月份和总和。
在这种情况下,状态中仅保留当前总和;新的对是通过使用
<$
运算符生成的,其中(,) String
的Functor
实例替换当前中的数字与状态中的总和配对,我认为使用
Data.Functor.($>)
(<$
的翻转版本)可能更具可读性,如果您选择的话这条路线。从视觉上看,如果您不需要映射
get
,它更类似于您可以编写的内容:x $>; y == (fst x, y)
。The list monad models nondetermism: do the same thing to each element of the list, then collect the results in a new list.
For the type of sequential traversal you want (do something to an element, then use the result to do something to the next element, etc), you can use the
State
monad to do something likeAt each step, the new state is the current month and the sum
of the old state's number and the current number.
traverse
accumulatesthose states in a list while traversing the original list.
You can also keep only the sum in the state, rather than a month that just gets replaced and the sum.
In this case, only the current sum is kept in the state; the new pair is generated by using the
<$
operator, which theFunctor
instance of(,) String
to replace the number in the current pair with the sum in the stateI think using
Data.Functor.($>)
(the flipped version of<$
) might be more readable, if you choose this route.Visually, it's more similar to what you could write if you didn't need to map over
get
:x $> y == (fst x, y)
.