Reduce in VB

Don Box's Spoutlet

Syndication

I was happy to see explicit support for reduce (a.k.a. fold) in the language.

Dim numbers%() = {1, 2, 3, 4, 5}

Dim n = Aggregate a In numbers Into Sum()

Thanks to Amanda Silver for helping me figure out why type inferencing wasn't acting the way I expected.

 


Posted Nov 14 2007, 08:57 PM by don-box

Comments

Keith Hill wrote re: Reduce in VB
on 11-19-2007 3:13 PM
So what is with the Dim numbers%() syntax? BTW this can be done in PowerShell fairly elegantly also:

1..5 | reduce-object

Given this function def:

param($Seed, [scriptblock]$ReduceFunction={param($1,$2) $1 + $2})

begin { $result = $Seed }

process {
if ($_) {
$result = &$ReduceFunction $result $_
}
}

end { $result }
Keith Hill wrote re: Reduce in VB
on 11-19-2007 3:24 PM
Hopefully this function defintion is easier to read:

function Reduce-Object($Seed, [scriptblock]$ReduceFunction={param($1,$2) $1 + $2})
{
begin { $result = $Seed }

process { if ($_) { $result = &$ReduceFunction $result $_ }}

end { $result }
}

Note that this function is "pipeline" aware which means that you can pipe sequences to it (as well as specify the aggregation function) e.g.:

1,3,5,7 | reduce-object -Seed 1 -ReduceFunction {param($1,$2) $1 * $2}
105

Add a Comment

(required)  
(optional)
(required)  
Remember Me?