Skip to content

Instantly share code, notes, and snippets.

@koher
Created June 24, 2022 00:44
Show Gist options
  • Save koher/b5b73217e68f95b33f32f5b015652ff2 to your computer and use it in GitHub Desktop.
Save koher/b5b73217e68f95b33f32f5b015652ff2 to your computer and use it in GitHub Desktop.
import CoreGraphics
let vectors: [CGVector] = [CGVector(dx: 2, dy: 1), CGVector(dx: -3, dy: 0)]
// ∞ノルムの平均の計算
// extension なし
vectors.lazy
.map { max($0.dx.magnitude, $0.dy.magnitude) }
.reduce(0, +) / CGFloat(vectors.count)
// extension あり
vectors.lazy.map(\.infNorm).mean()
// private extension
private extension CGVector {
var infNorm: CGFloat { max(dx.magnitude, dy.magnitude) }
}
private extension Collection where Element: FloatingPoint {
func mean() -> Element {
reduce(0, +) / Element(count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment