python’s yield is useful in fib
from itertools import islice
def fib():
a = 0
b = 1
while True:
a, b = b, a + b
yield a
for i in islice(fib(), 10):
print(i)
RIIR
use std::iter::{from_fn, successors};
fn fib_sequence() -> impl Iterator<Item = u128> {
let mut a = 0;
let mut b = 1;
from_fn(move || {
[a, b] = [b, a + b];
Some(a)
})
}
fn fib_sequence1() -> impl Iterator<Item = u128> {
successors(
Some((0, 1)), //
|&(a, b)| Some((b, a + b)),
)
.map(|(_, b)| b)
}
fn main() {
fib_sequence().take(5).for_each(|x| println!("{x}"));
fib_sequence1().take(5).for_each(|x| println!("{x}"));
}
RIIP
from itertools import islice
from typing import Callable, Tuple
def successors(init: Tuple[int, int], n: Callable[[int, int], Tuple[int, int]]):
yield init
yield from successors(n(*init), n)
for _, i in islice(successors((0, 1), lambda x, y: (y, x + y)), 10):
print(i)
but I haven’t figure how to get it from recursive function…
may help,use struct + closure function to acted like outside。
in py,we make a iter,then yield。then add a function at its outside。
but in rust,we change the form of function。
sum => a + b
max => max(a, b)
prod => a * b
count => 1
^ the above content can be found from
the algebra of programming
foldl + op can get new op.
事实上, 考虑这样一个过程
ans = op::default()
for i in 可迭代对象:
ans = op(ans, i)
ans
用线性的写法就是
op(op(op(op(op(ans, i1), i2), i3), i4), i5)