Created
October 27, 2016 13:55
-
-
Save cdhunt/4fb6b097e0587e14a3c42e0f2f7d3c39 to your computer and use it in GitHub Desktop.
Map and Fold implementations in Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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