This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Rough cut at integrating foldLeft with list comprehensions

No replies
wrburdick
Joined: 2009-09-21,
User offline. Last seen 3 years 3 weeks ago.
Looking at ScalaQL made me wonder if it was possible to trick Scala into supporting folding in a list comprehension.  This is what I came up with.  I'm just playing around with an idea here, not suggesting that people actually use this code, by the way, but I think it's worth looking at.
val l = 1 to 3 val f = new Fold(0) println((for { i <- l a <- f } yield a + i).last)
It prints "6" (which is the result of (1 to 3).foldLeft(0)(_ + _), or, the ever popular: (0 /: l)(_ + _)).  Making Fold support the comprehension protocol and providing an implicit def to convert Folds to Lists, gives you a list of intermediate foldLeft values (the last value being the result).
My Fold rough cut depends on side effects and it doesn't work if you put the "new Fold(0)" inside the for statement, because it makes a new Fold object for each element of r.  Also, the way it's written, Fold can't be the first element of the for or it will require all the other statements to convert to Fold objects.  There's probably a better way to write it.  Fold's map is defined like this:
def map[B](f: A => B): Fold[B] = { oldValue = f(oldValue.asInstanceOf[A]) new Fold(oldValue.asInstanceOf[B]) }
I dunno, but it makes sense to me to have list comprehensions support folding.  Maybe something like this, some day?
for { foldLeft a <- 0 i <- List(1,2,3 4)} yield a + i
with foldLeft changing the for statement so that is returns the result of the fold instead of a list.
Or something?

I'm attaching the code, for reference (it's very small).

-- Bill

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland