Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Functional programming 科特林';具有不同类型的s reduce()函数_Functional Programming_Kotlin - Fatal编程技术网

Functional programming 科特林';具有不同类型的s reduce()函数

Functional programming 科特林';具有不同类型的s reduce()函数,functional-programming,kotlin,Functional Programming,Kotlin,我查看了数组扩展函数,发现reduce()one inline fun <S, T: S> Array<out T>.reduce(operation: (acc: S, T) -> S): S { if (isEmpty()) throw UnsupportedOperationException("Empty array can't be reduced.") var accumulator: S = this[0] fo

我查看了数组扩展函数,发现
reduce()
one

inline fun <S, T: S> Array<out T>.reduce(operation: (acc: S, T) -> S): S {
    if (isEmpty())
        throw UnsupportedOperationException("Empty array can't be reduced.")
    var accumulator: S = this[0]
    for (index in 1..lastIndex) {
        accumulator = operation(accumulator, this[index])
    }
    return accumulator
}
似乎大多数使用此函数的实际用例都使用此签名:

inline fun <T> Array<out T>.reduce(operation: (acc: T, T) -> T): T
inlinefun数组.reduce(操作:(acc:T,T)->T):T
您能否帮助提供一些示例,其中
reduce()
函数对于不同类型的应用非常有用。

以下是一个示例:

interface Expr {
    val value: Int
}

class Single(override val value: Int): Expr

class Sum(val a: Expr, val b: Expr): Expr {
    override val value: Int
        get() = a.value + b.value
}

fun main(args: Array<String>) {
    val arr = arrayOf(Single(1), Single(2), Single(3));
    val result = arr.reduce<Expr, Single> { a, b -> Sum(a, b) }
    println(result.value)
}
接口表达式{
val值:Int
}
单个类(覆盖值:Int):Expr
类和(val a:Expr,val b:Expr):Expr{
覆盖值:Int
get()=a.value+b.value
}
趣味主线(args:Array){
val arr=阵列(单个(1)、单个(2)、单个(3));
val result=arr.reduce{a,b->Sum(a,b)}
println(结果值)
}
interface Expr {
    val value: Int
}

class Single(override val value: Int): Expr

class Sum(val a: Expr, val b: Expr): Expr {
    override val value: Int
        get() = a.value + b.value
}

fun main(args: Array<String>) {
    val arr = arrayOf(Single(1), Single(2), Single(3));
    val result = arr.reduce<Expr, Single> { a, b -> Sum(a, b) }
    println(result.value)
}