我认为Ignacio的解决方案几乎是正确的,但需要类型的运算符(‘a – >’a – >’a)并且不会产生第一个元素.
def scan(f, state, it):
for x in it:
state = f(state, x)
yield state
# test
>>> snoc = lambda xs,x: xs+[x]
>>> list(scan(snoc, [], 'abcd'))
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]
>>> list(scan(operator.add, 0, [1,2,3]))
[1,3,6]
具体来说,Seq.scan的类型是
('State -> 'T -> 'State) -> 'State -> seq -> seq
Python中的默认方法是使用该类型编写扫描
('State -> 'State -> 'State) -> seq -> seq
这来自Python指定reduce的方式,默认情况下它具有相同的类型.