forked from JetBrains/kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumeric.kt
56 lines (48 loc) · 1.65 KB
/
Numeric.kt
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)
}
}
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 {
fun checkOverflow(value: String) = if (f == Family.Sequences || f == Family.Iterables) "checkCountOverflow($value)" else value
"""
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
${checkOverflow("++count")}
}
return if (count == 0) Double.NaN else sum / count
"""
}
}
}