Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created August 31, 2013 13:50
Show Gist options
  • Save gclaramunt/6398308 to your computer and use it in GitHub Desktop.
Save gclaramunt/6398308 to your computer and use it in GitHub Desktop.
object Multifold{
// monotyped "multifold"
def multiFold[A,B](fs:List[(A,B)=>A])(zeros:List[A])(xs:List[B]):List[A]=
xs.foldLeft(zeros)(
(as,b)=> fs.zip(as).map({case (f,a)=>f(a,b)}) // or better: applicative functor
)
}
/*
scala> val fs=List((x:Int,y:Int)=>x+y, (x:Int,y:Int)=>x+1)
fs: List[(Int, Int) => Int] = List(<function2>, <function2>)
scala> val data=List(1,2,3,4,5,6)
data: List[Int] = List(1, 2, 3, 4, 5, 6)
scala> val zeros=data.map(x=>0)
zeros: List[Int] = List(0, 0, 0, 0, 0, 0)
scala> multiFold(fs)(zeros)(data)
res1: List[Int] = List(21, 6)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment