List-Partition in PowerShell

by Doug Finke on September 25, 2008

in Functional Programming,PowerShell

Partitions a list based on a predicate. The first list contain the elements that match and the second the ones that don’t.

Function List-Partition {
 param($fun, $list)

 $list1=@(); $list2=@()

 $list |
   ForEach {
     if(& $fun $_) {
       $list1+=@($_) } else {$list2+=@($_)
     }
 }

 $list1, $list2
}

Works with a simple list

$numList = 1,2,3,5,7,11,13,16,17,19,23
$fun = {param($x) $x % 2 -eq 0}

$list1,$list2 = List-Partition $fun $numList
"[$list1] [$list2]"
Results

[2 16] [1 3 5 7 11 13 17 19 23]

Works with a list of Objects

$list = @()
$list += New-Person John Doe
$list += New-Person Jane Doe
$list += New-Person Tom Doe
$list += New-Person Harry Doe
$list += New-Person George Carlin
$list += New-Person Lenny Bruce

$list1,$list2 = List-Partition {param($x) $x.Last -eq 'Doe'} $list
"List1"
$list1

"`nList2"
$list2
Results

image

{ 2 comments… read them below or add one }

kov 09.26.08 at 10:29 am

Hi Doug, nice code. Perhaps I’m opening a tangent here, but curious about how tough PoSH’s typing is. If $fun returned something other than a boolean (what if it returned a string?), would it get through the parser? In other words, is are function-types distinguished by their parameter-types?

Doug Finke 09.26.08 at 10:38 am

Good point. F# would catch that at compile time.

PowerShell does not.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>