Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active January 3, 2016 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/9507f44125dc97c89fdf to your computer and use it in GitHub Desktop.
Save guitarrapc/9507f44125dc97c89fdf to your computer and use it in GitHub Desktop.
function unfoldr([scriptblock] $f, $b) {
while($true) {
$it = &$f($b)
if ($it -eq $null) {
# f b == Nothing
break
} else {
# f b == Just (a,b)
,$a, $b = $it
,$a
}
}
}
function Select-Queue
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline = $true)]
$InputObject,
[int]$First
)
begin
{
Add-Type -TypeDefinition @"
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Reflection;
public class NewError
{
private static readonly Type StopUpstreamCommandsExceptionType = Assembly.GetAssembly(typeof (PSCmdlet)).GetType("System.Management.Automation.StopUpstreamCommandsException");
public Exception StopUpstreamCommandsException(Cmdlet cmdlet)
{
var stopUpstreamCommandsException = (Exception) Activator.CreateInstance(StopUpstreamCommandsExceptionType,
BindingFlags.Default | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public,
null,
new Object[] {(InternalCommand) cmdlet},
null
);
return stopUpstreamCommandsException;
}
}
"@
$queue = New-Object "System.Collections.Queue";
}
process
{
foreach($item in $InputObject){ $queue.Enqueue($item); }
try
{
$InputObject;
if ($queue.Count -eq $First)
{
$null = $queue;
# must use [CmdletBindig()] for Auto variables $PSCmdlet
throw (New-Object NewError).StopUpstreamCommandsException($PSCmdlet);
}
}
catch
{
# grab exception to remove any error message
break;
}
}
}
$x = unfoldr {param($x) ,$x,$x } 1 | Select-Queue -First 5; $x
<#
1
1
1
1
1
#>
trap {continue}; $y = unfoldr {param($x) ,$x,$x } 1 | Select-Queue -First 5; $y
<#
1
1
1
1
1
#>
$x = 1..10 | Select-Queue -First 5; $x;
<#
1
2
3
4
5
#>
unfoldr {param($x) ,$x,$x } 1 | Select-Queue -First 1 | %{$_}
<#
1
#>
$x = unfoldr {param($x) ,$x,$x } 1 | Select-Queue -First 1; $x | %{$_};
<#
1
#>
# As Select-Object -First also not support Parameter Input with -First
Select-Object -InputObject (1..10) -First 5
# Select-Queue also not support it
Select-Queue -InputObject (1..10) -First 5
$result = "初期値";
$result = &{end{foreach($i in (1..100)){$i}}} |Select-Queue -First 10;
$result;
<#
1
2
3
4
5
6
7
8
9
10
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment