Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Map and Fold implementations in Powershell
function map([scriptblock]$map, [Collections.IEnumerable]$x, $y) { $x.ForEach({& $map $_ $y}) }
# Two parameters
map { param($x, $y) $x + $y } @(1,2,3) 10
# Anonymous function as a value
$squareIt = { param($x) $x + $x }
map $squareIt @(1,2,3)
# One parameter
map { param($x) [math]::Pow($x,2) } @(1,2,3)
# Strings
map { param($x,$y) ' ' * ($y - $x.Length) + $x } (echo bob chris jack) 12
function fold([scriptblock]$fold, [Collections.IEnumerable]$x, $a) {
$x.ForEach({
$a = & $fold $a $_
})
return $a
}
$sum = { param($a,$x) $a + $x }
# Basic aggregation
fold $sum @(1,2,3)
# With initializer
fold { param($a,$x) $a + $x } @(1,2,3) 1
# Combining functions
fold $sum (map $squareIt @(1,2,3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.