PoshCode Archive  Artifact [42c9b71704]

Artifact 42c9b71704a06424ae7657e9679c74a96266e65b90ddac63079d4f851fd63fa4:

  • File gather-take.ps1 — part of check-in [d4a4299a63] at 2018-06-10 13:50:15 on branch trunk — Port of Perl 6’s gather/take (which itself is a port of Mathematica’s Reap/Sow) (user: Public Domain size: 1148)

# encoding: ascii
# api: powershell
# title: gather/take
# description: Port of Perl 6’s gather/take (which itself is a port of Mathematica’s Reap/Sow)
# version: 0.1
# type: function
# author: Public Domain
# license: CC0
# x-poshcode-id: 5119
# x-archived: 2014-05-02T00:17:21
# x-published: 2014-04-26T23:37:00
#
#
function gather {
#.SYNOPSIS
#  Port of Perl 6's gather/take (which itself is a port of Mathematica's Reap/Sow)
#.EXAMPLE
#  gather { 1 ; take 2 ; 3 ; take 4 5 }
#  2
#  4
#  5
#.NOTES
#  PowerShell doesn't really need this since the pipeline does this by default
#  (and does a much better job since it works by using a push streaming model)
#  but it's useful in the rare cases that it's necessary.
	[CmdletBinding()]
	param(
		[Parameter(Mandatory)]
		[scriptblock]$Script
	)
	try {
		${function:take} = (New-Object System.Management.Automation.PSModuleInfo $true).NewBoundScriptBlock({ $script:acc.AddRange($args) })
		& ${function:take}.Module { $script:acc = [System.Collections.ArrayList]@() }
	} catch {
		throw
	}
	$null = & $Script
	& ${function:take}.Module { $script:acc }
}