Skip to content

Instantly share code, notes, and snippets.

@cdhunt
Created October 27, 2016 13:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cdhunt/4fb6b097e0587e14a3c42e0f2f7d3c39 to your computer and use it in GitHub Desktop.
Save cdhunt/4fb6b097e0587e14a3c42e0f2f7d3c39 to your computer and use it in GitHub Desktop.
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