Martin Mucha
Martin Mucha

Reputation: 3091

how is reduce defined (using foreach)

I'm having hard time understanding how to use foreach. I kinda "understands" the text, but the example given in manual is little bit over my head. Can you please show me how to define reduce operation using foreach?

Upvotes: 0

Views: 133

Answers (1)

ikegami
ikegami

Reputation: 386386

reduce SOURCE as $VAR (INIT; REDUCTION)

is equivalent to

[ foreach SOURCE as $VAR (INIT; REDUCTION; .) ] | last

Conversely,

foreach SOURCE as $VAR (INIT; UPDATE; EXTRACT)

is equivalent to

reduce SOURCE as $VAR (
   { state: ( INIT ), rv: [] };
   .state |= ( UPDATE ) |
   .rv += [ .state | EXTRACT ]
) | .rv[]

A you can see, they are very similar. Practically identical, in fact.

  • Use reduce when you want a single result.
  • Use foreach when you want a result for each input.

For example, say we have the following input:

["abc", "def", "ghi", "jkl", "mno"]
foreach .[] as $var (false; not; .)

produces

true
false
true
false
true

so

foreach .[] as $var (false; not; if . then $var else empty end)

produces

"abc"
"ghi"
"mno"

Upvotes: 2

Related Questions