Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Two accumulators in reduce / fold

Suppose I have a data list val data = listOf("F 1", "D 2", "U 1", "D 3", "F 10") and I wanna perform the given logic on each element.

I have to add var acc2 = 0 outside to do this. I wonder is there any possible to get two accumulators in fold / reduce that this method be without side effect.

val data = listOf("F 1", "D 2", "U 1", "D 3", "F 10")
var acc2 = 0
val result = data.fold(0, { acc, str ->
    when (str.split(" ")[0]) {
        "F" -> {
            acc + str.split(" ")[1].toInt() * acc2
        }
        "D" -> {
            acc2 += str.split(" ")[1].toInt()
            acc
        }
        "U" -> {
            acc2 -= str.split(" ")[1].toInt()
            acc
        }
        else -> {
            acc
        }
    }
})
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use a simple object, wrapping both values.

data class Position(var horizontal: Int, var depth: Int)

val data = listOf("F 1", "D 2", "U 1", "D 3", "F 10")

val result = data.fold(Position(0, 0)) { position, str ->
    val (command, value) = str.split(" ")

    when (command) {
        "F" -> position.horizontal += value.toInt()
        "D" -> position.depth += value.toInt()
        "U" -> position.depth -= value.toInt()
    }

    position
}

If you don't want to create a new class for this, you may utilize the class Pair<Int, Int> from the stdlib of Kotlin.

over 4 years ago · Santiago Trujillo Report

0

Thanks to above comments I have tried to use Pair in my solution

val result = data.fold(Pair(0, 0), { accs, str ->
    val (command, value) = str.split(" ")
    when (command) {
        "F" -> Pair(accs.first + value.toInt() * accs.second, accs.second)
        "D" -> Pair(accs.first, accs.second + value.toInt())
        "U" -> Pair(accs.first, accs.second - value.toInt())
        else -> accs
     }
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!