kotlin
  • Kotlin
  • Variable
  • Function
  • First Class Citizen
  • High Order Function
  • Pure Function
  • Call by Value, Call by Name
  • Null Safe
  • Generic
  • Expression
    • if - else
    • when
    • try - catch
    • while
    • for
  • Class
    • abstract
    • constructor
    • Data Class
    • Default Value
    • enum
    • inheritance
    • interface
    • open
    • property
    • sealed
  • Kotlin Standard
    • let
    • with
    • apply
    • run
    • also
    • takeIf
    • takeUnless
    • use
    • repeat
  • Collections
    • Mutable
    • Immutable
    • Collections
    • Aggregate operations
      • any
      • all
      • count
      • fold
      • foldRight
      • fold vs foldRight
      • forEach
      • forEachIndexed
      • max
      • maxBy
      • min
      • minBy
      • none
      • reduce
      • reduceRight
      • sum
      • sumBy
    • Filtering operations
      • drop
      • dropLast
      • dropWhile
      • dropLastWhile
      • filter
      • filterNot
      • slice
      • take
      • takeLast
      • takeWhile
    • Mapping operations
      • map
      • mapIndexed
      • flatMap
      • groupBy
    • Elements operations
      • contains
      • elementAt
      • elementAtOrElse
      • elementAtOrNull
      • first
      • firstOrNull
      • indexOf
      • indexOfFirst
      • indexOfLast
      • last
      • lastIndexOf
      • lastOrNull
      • single
      • singleOrNull
    • Generation operations
      • partition
      • plus
      • minus
      • zip
      • unzip
    • Ordering operations
      • reversed
      • sorted
      • sortedBy
      • sortedDescending
      • sortedByDescending
Powered by GitBook
On this page
  1. Collections
  2. Aggregate operations

fold vs foldRight

val list = listOf("a", "b", "c", "d", "e")

println(list.foldRight("", { pre, acc -> pre + acc }))  // "abcde"
println(list.fold("", { acc, next -> acc + next })) // "abcde"

println(list.foldRight("", { pre, acc -> "($pre + $acc)" }))
// (a + (b + (c + (d + (e + )))))
println(list.fold("", { acc, next -> "($acc + $next)" }))
// ((((( + a) + b) + c) + d) + e)

val stringBuilderFR = StringBuilder()
println(list.foldRight(stringBuilderFR, { pre, acc -> stringBuilderFR.append(pre) } ))
// edcba

val stringBuilderFL = StringBuilder()
println(list.fold(stringBuilderFL, { acc, next -> stringBuilderFL.append(next) } ))
// abcde
  • 우선순위가 있는, 순서가 있는 연산에 대해서는 두개의 특징을 잘 알고 사용하는 것이 좋다.

  • 우선순위가 끝쪽이 더 높다 하는 경우에는 foldRight 를, 우선순위가 왼쪽에 있는 값부터 해야한다 하는 경우 일반적인 fold 를 사용하면 좋다.

PreviousfoldRightNextforEach

Last updated 6 years ago