За простую элегантную простоту я люблю:
// 1. Calls #3
func average (_ values: T...) -> T where T: FloatingPoint
{
return sum(values) / T(values.count)
}
Пока мы на нем, другие приятные reduce
операции на основе:
// 2. Unnecessary, but I appreciate variadic params. Also calls #3.
func sum (_ values: T...) -> T where T: FloatingPoint
{
return sum(values)
}
// 3.
func sum (_ values: [T]) -> T where T: FloatingPoint
{
return values.reduce(0, +)
}
Предоставлено: MathKit Адриана Гударта, в основном без изменений.
Я нашел следующее в Язык программирования Swift :
В приведенном ниже примере вычисляется среднее арифметическое (также известно как среднее значение) для списка чисел любой длины:
func arithmeticMean(_ numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1, 2, 3, 4, 5) // returns 3.0, which is the arithmetic mean of these five numbers arithmeticMean(3, 8.25, 18.75) // returns 10.0, which is the arithmetic mean of these three numbers
Вы можете использовать оператор -match
, чтобы переформулировать вашу команду как:
some-command | Foreach-Object { if($_ -match '^(//[^#]*)') { some-other-command $($matches[1])}}
Вы можете попробовать следующее:
Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value }