Unwrap the closure pls - confusion about iter::fold() and closures

let mut ctx = Context { keychain };
let (mut tx, sum) = elems.iter().fold(
	(Transaction::empty(), BlindSum::new()),
	|acc, elem| elem(&mut ctx, acc),
);

i mean
(Transaction::empty(), BlindSum::new()) - initial object
|acc, elem| - accumulator and current
but how interpret
elem(&mut ctx, acc)
?

It looks like elem is a function or closure which you are calling with two parameters, and it must return the same accumulator type for the fold.

there is no declared function with 'elem' name

https://github.com/mimblewimble/grin/blob/master/core/src/core/build.rs#L191

there is no declared function with ‘elem’ name

|acc, elem| elem(&mut ctx, acc)

This is a closure taking two parameters acc and elem, returning what elem is returning. Makes sense?

The type definition for the closures Trait is here;
https://github.com/mimblewimble/grin/blob/master/core/src/core/build.rs#L43

let (mut tx, kern, sum) = elems.iter().fold(
	(Transaction::empty(), TxKernel::empty(), BlindSum::new()),
	|acc, elem| elem(&mut ctx, acc),
);

then what will result of fold? last item in elems?

Elems are the Closures being iterated over. The result of the fold will be the return value of the last call to last closure in the elems vec. Its input depends on prior accumulated values. (If elems is empty then it is just the initial value.)

thanks a lot
i have found how elems are prepared...
removal of the brain

1 Like