Weitere ähnliche Inhalte
Ähnlich wie Protocol-Oriented Integers に想うジェネリックプログラミングの未来 (6)
Mehr von Tomohiro Kumagai (20)
Protocol-Oriented Integers に想うジェネリックプログラミングの未来
- 7. func sum<T : Numeric>(of values: Array<T>) -> T {
return values.reduce(0) { $0 + $1 }
}
// Int の配列でも、Float の配列でも、使える
let integers = [5, 5, 5, 5]
let floats = [2.5, 2.5, 2.5, 2.5] as [Float]
sum(of: integers) // 20
sum(of: floats) // 10
- 10. func average <C:Collection> (of values: C ) -> C.Element
where C.Element : BinaryInteger {
return values.reduce(into: 0, +=) / C.Element(values.count)
}
- 12. extension Array {
// 変換元は、要素の型が同じならどんな Sequence でも良い
init<S:Sequence>(_ s: S) where Element == S.Element
}
// どんな Sequence も配列型に変換できる
Array([1, 5, 8, 3, 7, 3]) // Array
Array([1, 5, 8, 3, 7, 3][2 ..< 5]) // ArraySlice
Array(1 ..< 20) // CountableRange
Array(zip([1, 3, 5], [2, 4, 6])) // Zip2Sequence<Array, Array>
- 13. // この書き方はパッと思いつかなくても、
func sum<T : Numeric>(of values: Array<T>) -> T {
return values.reduce(into: 0, +=)
}
// こちらなら自然と書ける人も多いはず(上記より Swift らしいと思う)
extension Array where Element : Numeric {
func sum() -> Element {
return reduce(into: 0, +=)
}
}
- 17. // Swift 1 は“写像(map)”が主体
func map<C:CollectionType, T>(source: C,
transform: (C.Generator.Element) -> T) -> [T]
// Swift 2 は“コレクション”が主体
extension CollectionType {
func map<T>(transform: (Generator.Element) -> T) -> [T]
}
- 20. func areaOfCircle<T:FloatingPoint>(withRadius radius: T) -> T {
return radius * radius * T.pi
}
areaOfCircle(withRadius: 2 as Double) // 12.566370614359172
areaOfCircle(withRadius: 2 as Float) // 12.56637
areaOfCircle(withRadius: 2 as Float80) // 12.566370614359172464
- 22. extension String {
// 現在主流の API
func repeated(_ count: Int) -> String
// Protocol-Oriented Integers を用いた API
func repeated<T:BinaryInteger>(_ count: T) -> String
}
"*".repeated(5) // "*****"