xlogI125’s blog

パソコン作業を効率化したい

PowerShell練習 ScriptBlock

Docs の about_Script_Blocks を参照してください。

# PowerShell 5.1
# Windows 10
# このスクリプトをメモ帳で保存する際は、
# 文字コードを UTF-8(BOM付き) として保存してください。

Set-StrictMode -Version Latest

$f0 = {
    param([double[]]$x)
    Write-Host ('$f0: $x' + " #=> " + "$x")
    $x[0] *= 3
    $x[1] *= 4
    Write-Host ('$f0: $x' + " #=> " + "$x")
    return $x
}.GetNewClosure()

$f1 = {
    param([double[]]$x)
    Write-Host ('$f1: $x' + " #=> " + "$x")
    $x[0] *= 5
    $x[1] *= 6
    Write-Host ('$f1: $x' + " #=> " + "$x")
    return $x
}.GetNewClosure()

$f2 = {
    param([double[]]$x)
    Write-Host ('$f2: $x' + " #=> " + "$x")
    $x[0] *= 7
    $x[1] *= 8
    Write-Host ('$f2: $x' + " #=> " + "$x")
    return $x
}.GetNewClosure()

# 見た目が何となくC言語で関数ポインタの配列を扱う場合を連想するような書き方
$f = @($f0, $f1, $f2)
Write-Output ('$($f.GetType().FullName)' + " #=> " + "$($f.GetType().FullName)")
Write-Output ('$($f[0].GetType().FullName)' + " #=> " + "$($f[0].GetType().FullName)")

$a = 0.1
$b = 0.2
$x = @($a, $b)
Write-Output ('$x' + " #=> " + "$x")

$x = &$f[0] $x
Write-Output ('$x' + " #=> " + "$x")

$x = &$f[1] $x
Write-Output ('$x' + " #=> " + "$x")

$x = &$f[2] $x
Write-Output ('$x' + " #=> " + "$x")

function Func([scriptblock]$f, [double[]]$x) {
    return &$f $x
}

$c = 1
$d = 2
$y = @($c, $d)
Write-Output ('$y' + " #=> " + "$y")

$y = Func -f $f[0] -x $y
Write-Output ('Func -f $f[0] -x $y' + " #=> " + $y)

$y = Func -f $f[1] -x $y
Write-Output ('Func -f $f[1] -x $y' + " #=> " + $y)

$y = Func -f $f[2] -x $y
Write-Output ('Func -f $f[2] -x $y' + " #=> " + $y)