2

Is there a PowerShell equivalent to the 'zip' from functional programming?

What is zip (functional programming?)

I want to take two input sequences and return a sequence of tuples containing the paired elements. Is there a built-in method or something built-in to the language that makes this easy?

BTW, I want the solution to be very 'natural' for PowerShell and integrate with the pipeline.

Community
  • 1
  • 1
Josh Petitt
  • 9,371
  • 12
  • 56
  • 104

3 Answers3

2

This request has come up from time to time. The idiomatic PowerShell solution would be a Join-Object command. The PowerShell team wrote this script along with some examples of using it on their blog - http://blogs.msdn.com/b/powershell/archive/2012/07/13/join-object.aspx

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
1

A bit cumbersome, but it works:

Script file test.ps1:

param( $fnop, $first, $second)

$retval = @()
$len = if($first.length -lt $second.length) { $first.length } else { $second.length }
for( $i = 0; $i -lt $len; $i++) {
    $oprslt = $fnop.invoke( $first[$i], $second[$i])
    $retval = $retval + $oprslt
}

$retval

Example:

 # add and sort
 PS> .\test.ps1 {param($a,$b) return $a+$b} (3,2,1) (8,-4,5) | sort
 11
 -2
 6

 # add only
 PS> .\test.ps1 {param($a,$b) return $a+$b} (3,2,1) (8,-4,5)
 -2
 6
 11

 # multiply and sort
 PS> .\test.ps1 {param($a,$b) return $a*$b} (3,2,1) (8,-4,5) | sort
 -8
 5
 24

The function block {param($a,$b) return $a+$b} is your zip function.

JensG
  • 13,148
  • 4
  • 45
  • 55
  • Thanks @JensG, I will study this. I like the way you passed the function in as the first argument, that makes sense. Do you think accepting the $first and $second parameter from the pipeline is more "PowerShell"-ish? I tried writing a version of this that uses the pipeline, but end the end I collected all the pipeline input before working with it, so it is essentially the same as your function. – Josh Petitt Nov 13 '14 at 17:32
  • Let me put it this way: It does what you wanted. There may be a better or more idiomatic ("powershellish") solution that I'm not aware of right now. So I don't put any guarantees here ;-) – JensG Nov 13 '14 at 17:38
1

I just want to point out that you can use tuples natively in Powershell:

$q = [System.Tuple]::Create('One','Two')
$q.Item1
$q.Item2

This doesn't necessarily help you or even make sense for this situation, but I thought it might interest you.

jimhark
  • 4,938
  • 2
  • 27
  • 28
briantist
  • 45,546
  • 6
  • 82
  • 127