0

Is there a function in Scala, which is a hybrid of map and fold? I'd like not to use a temporary var variable. I want to return a list and at the same time be able to have an accumulator.

update:

I'd like to do this

  def findMaxSubarray(source: Seq[Int]) = {
    var lastSum = 0
    val maxes = source map { x =>
      lastSum += x
      if (lastSum < 0) lastSum = 0
      lastSum
    }

    maxes.max
  }

without using scalaz and var, only using standard scala library.

Incerteza
  • 32,326
  • 47
  • 154
  • 261
  • Related question: http://stackoverflow.com/questions/12261157/what-is-proper-monad-or-sequence-comprehension-to-both-map-and-carry-state-acros – Ionuț G. Stan Mar 04 '14 at 07:48

1 Answers1

3

For updated question

You could use scanLeft (or scan) like this:

val seq = Stream.continually(util.Random.nextInt(200) - 100).take(100)
val maxes = seq.scan(0){ (lastSum, i) => (lastSum + i) max 0 }
maxes.max
// Int = 547

It produces collection of all subresults of foldLeft

For initial question

There is such method in scalaz: foldMap.

(0 to 2).toList.foldMap{_ + 1}
// Int = 6

It works for monoids, zero is used as initial value:

(0 to 2).map{_ + 1}.fold(Monoid[Int].zero){_ |+| _}

There is no such method in standard scala library, but you could use view before map to avoid intermediate collection creation:

(0 to 2).view.map{_ + 1}.fold(0){_ + _}
Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129