Here's a random fold from code I've written in another language:

  let (a, b, c, d) = (Some(1), Some(2), Some(3), None;
  let sum = [a, b, c, d].iter().fold(0, |acc, n| acc + n.unwrap_or(0));

This is roughly equivalent to

  orzero =: ]`0: @. (128!:5)
  'a b c d' =: 1 2 3 _.
  sum =: +/orzero a, b, c, d

Summing numbers in the list if they're numbers, while just
treating them as zero if they're an exceptional value instead
of a number.

What's important about that example is the 'acc'. Probably 99%
of my folds in any language have one parameter named 'acc',
which is short for 'accumulator', which has the type of the
result of the fold rather than the type of the data input to
the fold. In the code above, 'acc' is just an integer sum, but
it's already not the same as the data input, which are optional
integers (allowing for None instead of Some(123)), and the
initial 'acc' is already provided separately from the data
(it's the 0 in fold(0, ...)).

Folds are powerful precisely because of this 'acc' variable.
You want a sum? Make it a number. You want a sum and also a
count of the inputs? Make it a pair of numbers. You want a sum
and also accumulated timings or anything else? Put that in as
well. The normal experience of writing folds in every single
language where they get use involves deciding on a non-data
input to the fold that will accumulate intermediate state from
the application of the fold over its data, and from which the
useful result of the fold will be derived.

i.e., the normal experience of using fold is deciding on your
control-like input. Which makes it idiomatically an x argument
in J, even if in other languages it varies (confusingly, and on
right-folds) purely over historical implementation reasons
rather than careful design.

On 2021-02-25 10:00, Hauke Rehr wrote:
...
• the silent majority most likely doesn’t see a problem here
  so “only Henry” ist most likely Very Wrong™


Am 25.02.21 um 16:22 schrieb 'Sergey Kamenev' via Programming:
...
And only Henry Rich thinks that everything with Fold is OK.
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to