programing

Powershell에는 Aggregate/Reduce 기능이 있습니까?

magicmemo 2023. 7. 25. 20:51
반응형

Powershell에는 Aggregate/Reduce 기능이 있습니까?

관련 질문이 있다는 것은 알지만, 모든 답변은 문제의 핵심을 피하는 해결책인 것 같습니다.powershell에 스크립트 블록을 사용하여 어레이의 요소를 단일 값으로 집계할 수 있는 작업이 있습니까?이것은 다른 언어에서 알려진 것입니다.aggregate또는reduce또는fold.

제가 직접 작성하는 것은 꽤 쉽지만, 목록 처리의 기본 작업이라는 점을 감안할 때, 제가 모르는 무언가가 내장되어 있다고 생각합니다.

그래서 제가 찾고 있는 것은 이런 것입니다.

1..10 | Aggregate-Array {param($memo, $x); $memo * $x}

Reduct-Object라는 이름은 없지만 Foreche-Object로 목표를 달성할 수 있습니다.

1..10 | Foreach {$total=1} {$total *= $_} {$total}

BTW 또한 일치하는 속성을 기준으로 두 개의 데이터 시퀀스를 병합하는 조인-오브젝트가 없습니다.

최대값, 최소값, 합계 또는 평균이 필요한 경우 사용할 수 있습니다.Measure-Object슬프게도 다른 집계 방법을 처리하지 않습니다.

Get-ChildItem | Measure-Object -Property Length -Minimum -Maximum -Average

이것은 제가 잠시 시작하고 싶었던 것입니다.이 질문을 보고, 방금 글을 썼습니다.pslinq(https://github.com/manojlds/pslinq) 유틸리티.현재 처음이자 유일한 cmdlet은Aggregate-List다음과 같이 사용할 수 있습니다.

1..10 | Aggregate-List { $acc * $input } -seed 1
#3628800

합계:

1..10 | Aggregate-List { $acc + $input }
#55

문자열 역방향:

"abcdefg" -split '' | Aggregate-List { $input + $acc }
#gfedcba

PS: 이건 실험에 가깝습니다.

최근에 비슷한 문제가 발생했습니다.여기 순수한 파워셸 솔루션이 있습니다.Javascript 버전과 같이 배열 및 문자열 내의 배열을 처리하지는 않지만 시작점이 좋을 수 있습니다.

function Reduce-Object {
    [CmdletBinding()]
    [Alias("reduce")]
    [OutputType([Int])]
    param(
        # Meant to be passed in through pipeline.
        [Parameter(Mandatory=$True,
                    ValueFromPipeline=$True,
                    ValueFromPipelineByPropertyName=$True)]
        [Array] $InputObject,

        # Position=0 because we assume pipeline usage by default.
        [Parameter(Mandatory=$True,
                    Position=0)]
        [ScriptBlock] $ScriptBlock,

        [Parameter(Mandatory=$False,
                    Position=1)]
        [Int] $InitialValue
    ) 

    begin {
        if ($InitialValue) { $Accumulator = $InitialValue }
    }

    process {
        foreach($Value in $InputObject) {
            if ($Accumulator) {
                # Execute script block given as param with values.
                $Accumulator = $ScriptBlock.InvokeReturnAsIs($Accumulator,  $Value)
            } else {
                # Contigency for no initial value given.
                $Accumulator = $Value
            }
        }
    }

    end {
        return $Accumulator
    }
}

1..10 | reduce {param($a, $b) $a + $b}
# Or
reduce -inputobject @(1,2,3,4) {param($a, $b) $a + $b} -InitialValue 2

제가 https://github.com/chriskuech/functional 에서 알게 된 기능 모듈이 있는데, reduced-object, merge-object, test-building 등이 있습니다.파워셸에 맵(각 객체에 대한)과 필터(where-object)가 있지만 감소하지 않는다는 것은 놀라운 일입니다.https://medium.com/swlh/functional-programming-in-powershell-876edde1aadb 심지어 javascript도 배열이 줄었습니다.환원제는 사실 매우 강력합니다.맵을 정의하고 이를 기준으로 필터링할 수 있습니다.

1..10 | reduce-object { $a * $b }

3628800

측정값-객체는 [시간 범위]의 값을 합계할 수 없습니다.

1..10 | % { [timespan]"$_" } | Reduce-Object { $a + $b } | ft

Days Hours Minutes Seconds Milliseconds
---- ----- ------- ------- ------------
55   0     0       0       0

두 개체 병합:

@{a=1},@{b=2} | % { [pscustomobject]$_ } | Merge-Object -Strategy fail

b a
- -
2 1

언급URL : https://stackoverflow.com/questions/25163907/does-powershell-have-an-aggregate-reduce-function

반응형