forked from JetBrains/kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumeric.kt
More file actions
56 lines (48 loc) · 1.54 KB
/
Numeric.kt
File metadata and controls
56 lines (48 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package templates
object Numeric : TemplateGroupBase() {
init {
defaultBuilder {
sequenceClassification(SequenceClass.terminal)
}
}
// TODO: use just numericPrimitives
private val numericPrimitivesDefaultOrder = PrimitiveType.defaultPrimitives intersect PrimitiveType.numericPrimitives
val f_sum = fn("sum()") {
Family.defaultFamilies.forEach { family -> include(family, numericPrimitivesDefaultOrder) }
} builder {
doc { "Returns the sum of all elements in the ${f.collection}." }
returns("SUM")
platformName("sumOf<T>")
body {
"""
var sum: SUM = ZERO
for (element in this) {
sum += element
}
return sum
"""
}
}
val f_average = fn("average()") {
Family.defaultFamilies.forEach { family -> include(family, numericPrimitivesDefaultOrder) }
} builder {
doc { "Returns an average value of elements in the ${f.collection}."}
returns("Double")
platformName("averageOf<T>")
body {
"""
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) Double.NaN else sum / count
"""
}
}
}