https://kotlinlang.org logo
#functional
Title
# functional
p

pavel

12/20/2018, 11:36 PM
or even
Copy code
fun testFun(nums: IntArray) =
    nums.fold(Int.MIN_VALUE to Int.MAX_VALUE) { (largest, smallest), next ->
        max(largest, next) to min(smallest, next)
    }.run { first - second }
h

Hexa

12/20/2018, 11:51 PM
thanks, i did not even know about the
run
function.
need to read up on it
u

Uzi Landsmann

12/21/2018, 8:06 AM
Why not just:
Copy code
fun testFun(nums: IntArray): Int {
    return nums.max()!! - nums.min()!!
}
d

Dias

12/21/2018, 10:28 AM
to avoid additional run over the collection
u

Uzi Landsmann

12/21/2018, 10:32 AM
Ok sure, if it’s a large list. Is it?
h

Hexa

12/21/2018, 4:09 PM
how does @Uzi Landsmann solution does additional run over? @Dias do both
nums.max()!!
and
nums.min()!!
iterates through the whole list
u

Uzi Landsmann

12/21/2018, 5:30 PM
Yes they do. If your list is large then you should consider a different solution.
👍 1
3 Views