본문 바로가기

IT/kotlin언어

[fold 함수] fold 함수 알아보기


안녕하세요 남갯입니다


오늘은 fold 함수에 대해 간단히 포스팅 해보려고합니다.



fold 함수는 


inline fun <TR> Array<out T>.fold(
    initial: R
    operation: (acc: R, T) -> R
)R


....

....


Accumulates value starting with initial value and applying operation from left to right to current accumulator value and each element.


-출처 https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold.html


초기값을 설정해주고 왼쪽부터 오른쪽까지 현재의 계산값에 각각을 적용하는 함수입니다.


val sumTotal = listOf(1,2,3,4,5).fold(0,{total,next -> total + next})
println("sumTotal : ${sumTotal}" )
// sumTotal : 15


위와같이 total이라는 변수의 초기값은 0으로 세팅한것이고 

total에 1부터 5까지를 더해 15가 나오는것을 확인 가능합니다.



val mulTotal = listOf(1,2,3,4,5).fold(1, {total,next -> total * next})
println("mulTotal : ${mulTotal}")
// mulTotal : 120


위와 같이 1의 초기값을 세팅 한 후 1부터 5까지의 곱을 하게되면

120이 나오는것을 확인 가능합니다.



data class Apple(val grade: String,val price: Int)
val appleList = listOf(
Apple("a++", 500),
Apple("a+", 400),
Apple("a", 300),
Apple("b", 200),
Apple("c", 100)
)

val applePrice = appleList.map { it.price }.fold(0, { total, next -> total + next })
println("applePrice : ${applePrice}")
// mulTotal : 1500



데이터객체의 경우에도 동일하게 이용 할 수 있습니다

map을 통해 사과의 가격만을 가져와 모든 사과의 가격을 합치는 함수로서의 표현도 가능합니다

값은 1500원이 나옵니다.