Scala Immutable MultiMap - scala

In Scala I would like to be able to write
val petMap = ImmutableMultiMap(Alice->Cat, Bob->Dog, Alice->Hamster)
The underlying Map[Owner,Set[Pet]] should have both Map and Set immutable. Here's a first draft for ImmutibleMultiMap with companion object:
import collection.{mutable,immutable}
class ImmutableMultiMap[K,V] extends immutable.HashMap[K,immutable.Set[V]]
object ImmutableMultiMap {
def apply[K,V](pairs: Tuple2[K,V]*): ImmutableMultiMap[K,V] = {
var m = new mutable.HashMap[K,mutable.Set[V]] with mutable.MultiMap[K,V]
for ((k,v) <- pairs) m.addBinding(k,v)
// How do I return the ImmutableMultiMap[K,V] corresponding to m here?
}
}
Can you resolve the comment line elegantly? Both the map and the sets should become immutable.
Thanks!

I've rewritten this same method twice now, at successive jobs. :) Somebody Really Oughta make it more general. It's handy to have a total version around too.
/**
* Like {#link scala.collection.Traversable#groupBy} but lets you return both the key and the value for the resulting
* Map-of-Lists, rather than just the key.
*
* #param in the input list
* #param f the function that maps elements in the input list to a tuple for the output map.
* #tparam A the type of elements in the source list
* #tparam B the type of the first element of the tuple returned by the function; will be used as keys for the result
* #tparam C the type of the second element of the tuple returned by the function; will be used as values for the result
* #return a Map-of-Lists
*/
def groupBy2[A,B,C](in: List[A])(f: PartialFunction[A,(B,C)]): Map[B,List[C]] = {
def _groupBy2[A, B, C](in: List[A],
got: Map[B, List[C]],
f: PartialFunction[A, (B, C)]): Map[B, List[C]] =
in match {
case Nil =>
got.map {case (k, vs) => (k, vs.reverse)}
case x :: xs if f.isDefinedAt(x) =>
val (b, c) = f(x)
val appendTo = got.getOrElse(b, Nil)
_groupBy2(xs, got.updated(b, c :: appendTo), f)
case x :: xs =>
_groupBy2(xs, got, f)
}
_groupBy2(in, Map.empty, f)
}
And you use it like this:
val xs = (1 to 10).toList
groupBy2(xs) {
case i => (i%2 == 0, i.toDouble)
}
res3: Map[Boolean,List[Double]] = Map(false -> List(1.0, 3.0, 5.0, 7.0, 9.0),
true -> List(2.0, 4.0, 6.0, 8.0, 10.0))

You have a bigger problem than that, because there's no method in ImmutableMultiMap that will return an ImmutableMultiMap -- therefore it is impossible to add elements to it, and the constructor does not provide support for creating it with elements. Please see existing implementations and pay attention to the companion object's builder and related methods.

Related

Scala: map just first element in tuple

I want to use some function on tuple, which returns tuple with only first element transformed and other elements unchanged.
This is naive version for Tuple2:
def mapFirst[T, U, R](tuple: (T, U))(f: T => R): (R, U) = tuple match {
| case (x, y) => f(x) -> y
| }
mapFirst((1, 2))(_ * 5) // returns (5, 2)
Though, it doesn't feel native, what I want is to write it this way:
(1, 2).mapFirst(_ * 5)
I wrote implicit conversion then:
class RichTuple[T, U](tuple: (T, U)) {
def mapFirst[R](f: T => R): (R, U) = tuple match {
case (x, y) => f(x) -> y
}
}
implicit def tuple2RichTuple[T, U](tuple: (T, U)): RichTuple[T, U] = new RichTuple(tuple)
(1, 2).mapFirst(_ * 5)
Then, when I'll want to map just second element or first element on Tuple3, I'll have to write same boilerplate again. Is there some library which has such methods built-in?
You can use shapeless tuple functions:
import shapeless._
import syntax.std.tuple._
val x=(1,2,3)
val y=x.updatedAt(0,x.head*5)
// y= (5,2,3)
We are able to use _1 as tuple's field. One more solution, just using standard library:
val x = (1, 2, 3)
val y = x.copy(_1 = x._1 * 5)
You could use case classes rather than tuples (this is good style) then use the named elements, e.g.
case class Pie(filling: String, weight: Double, servings: Int)
val p = Pie("cheese", 500.0, 2)
val q = p.copy(filling = "potato")
val r = p.copy(weight = 750.0, servings = 3)

Another Scala CanBuildFrom issue: a collection enrichment operator that wraps another of a different type

User Régis Jean-Gilles gracefully answered my previous question where I was struggling with CanBuildFrom and enrichment functions (aka "pimp my library" or "enrich my library"):
Creating an implicit function that wraps map() in Scala with the right type: Not for the faint at heart
But this time I've got an even more complicated issue.
I have a function to implement variations on intersectWith, for intersecting collections by their keys. I've managed to make them work like proper collection functions:
implicit class IntersectUnionWithPimp[K, A, Repr](a: GenTraversableLike[(K, A), Repr]) {
/**
* Intersect two collections by their keys. This is identical to
* `intersectWith` except that the combiner function is passed the
* key as well as the two items to combine.
*
* #param b Other collection to intersect with.
* #param combine Function to combine values from the two collections.
*/
def intersectWithKey[B, R, That](b: GenTraversable[(K, B)])(
combine: (K, A, B) => R)(
implicit bf: CanBuildFrom[Repr, (K, R), That]): That = {
...
}
/**
* Intersect two collections by their keys. Keep the ordering of
* objects in the first collection. Use a combiner function to
* combine items in common. If either item is a multi-map, then
* for a key seen `n` times in the first collection and `m`
* times in the second collection, it will occur `n * m` times
* in the resulting collection, including all the possible
* combinations of pairs of identical keys in the two collections.
*
* #param b Other collection to intersect with.
* #param combine Function to combine values from the two collections.
*/
def intersectWith[B, R, That](b: GenTraversable[(K, B)])(
combine: (A, B) => R)(
implicit bf: CanBuildFrom[Repr, (K, R), That]): That =
a.intersectWithKey(b){ case (_, x, y) => combine(x, y) }(bf)
}
Now, I currently also have non-CanBuildFrom versions of intersectBy and friends, and these I can't get working as CanBuildFrom versions.
implicit class IntersectUnionByPimp[A](a: Traversable[A]) {
/**
* Intersect two collections by their keys, with separate key-selection
* functions for the two collections. This is identical to
* `intersectBy` except that each collection has its own key-selection
* function. This allows the types of the two collections to be
* distinct, with no common parent.
*
* #param b Other collection to intersect with.
* #param key1fn Function to select the comparison key for the first
* collection.
* #param key1fn Function to select the comparison key for the first
* collection.
* #param combine Function to combine values from the two collections.
*/
def intersectBy2[K, B, R](b: Traversable[B])(key1fn: A => K
)(key2fn: B => K)(combine: (A, B) => R): Traversable[R] = {
val keyed_a = a.map { x => (key1fn(x), x) }
val keyed_b = b.map { x => (key2fn(x), x) }
keyed_a.intersectWith(keyed_b)(combine).map(_._2)
}
/**
* Intersect two collections by their keys. Keep the ordering of
* objects in the first collection. Use a combiner function to
* combine items in common. If either item is a multi-map, then
* for a key seen `n` times in the first collection and `m`
* times in the second collection, it will occur `n * m` times
* in the resulting collection, including all the possible
* combinations of pairs of identical keys in the two collections.
*
* #param b Other collection to intersect with.
* #param keyfn Function to select the comparison key.
* #param combine Function to combine values from the two collections.
*/
def intersectBy[K, B >: A](b: Traversable[B])(keyfn: B => K)(
combine: (A, B) => B): Traversable[B] = {
val keyed_a = a.map { x => (keyfn(x), x) }
val keyed_b = b.map { x => (keyfn(x), x) }
keyed_a.intersectWith(keyed_b)(combine).map(_._2)
}
}
The best version so far I can come up with is this:
implicit class IntersectUnionByPimp[A, Repr](a: GenTraversableLike[A, Repr]) {
def intersectBy2[K, B, R, That](b: Traversable[B])(key1fn: A => K)(
key2fn: B => K)(combine: (A, B) => R)(
implicit bf: CanBuildFrom[Repr, R, That]): That = {
// FIXME! How to make this work while calling `map`?
// val keyed_a = a.map { x => (key1fn(x), x) }
val keyed_a = mutable.Buffer[(K, A)]()
a.foreach { x => keyed_a += ((key1fn(x), x)) }
val keyed_b = b.map { x => (key2fn(x), x) }
keyed_a.intersectWith(keyed_b)(combine).map(_._2)
}
def intersectBy[K, B >: A, That](b: Traversable[B])(keyfn: B => K)(
combine: (A, B) => B)(
implicit bf: CanBuildFrom[Repr, B, That]): That = {
// FIXME! How to make this work while calling `map`?
// val keyed_a = a.map { x => (keyfn(x), x) }
val keyed_a = mutable.Buffer[(K, A)]()
a.foreach { x => keyed_a += ((keyfn(x), x)) }
val keyed_b = b.map { x => (keyfn(x), x) }
keyed_a.intersectWith(keyed_b)(combine).map(_._2)
}
First, I don't see why I need to rewrite the call to map that produces keyed_a with a mutable Buffer; seems like there must be a better way. But I still get the same sort of error on the bottom line:
[error] /Users/benwing/devel/textgrounder/src/main/scala/opennlp/textgrounder/util/collection.scala:1018: type mismatch;
[error] found : scala.collection.mutable.Buffer[R]
[error] required: That
[error] Note: implicit method bufferToIndexedSeq is not applicable here because it comes after the application point and it lacks an explicit result type
[error] keyed_a.intersectWith(keyed_b)(combine).map(_._2)
[error] ^
So my questions are:
How to call map on a GenTraversableLike?
How to make the call to intersectWith work correctly? I know I have to somehow pass in a CanBuildFrom based on the one I received, and I know about mapResult on Builders, but I'm not sure what to do here, or if this is even possible.
An example of intersectBy, which intersects lists of floating-point numbers treating two numbers the same if their integral part is the same, and computing the absolute difference:
scala> List(4.5,2.3,4.2).intersectBy(List(4.6,4.8))(_.toInt){ case (a,b) => (a - b).abs }
res2: Traversable[Double] = List(0.09999999999999964, 0.2999999999999998, 0.39999999999999947, 0.5999999999999996)
(except that the returned type should be List[Double])
Thanks for any help.
OK, turns out I need to create a builder to return the items, instead of trying to return them directly. The following works:
implicit class IntersectUnionByPimp[A, Repr](a: GenTraversableLike[A, Repr]) {
/**
* Intersect two collections by their keys, with separate key-selection
* functions for the two collections. This is identical to
* `intersectBy` except that each collection has its own key-selection
* function. This allows the types of the two collections to be
* distinct, with no common parent.
*
* #param b Other collection to intersect with.
* #param key1fn Function to select the comparison key for the first
* collection.
* #param key2fn Function to select the comparison key for the first
* collection.
* #param combine Function to combine values from the two collections.
*/
def intersectBy2[K, B, R, That](b: GenTraversable[B])(key1fn: A => K)(
key2fn: B => K)(combine: (A, B) => R)(
implicit bf: CanBuildFrom[Repr, R, That]): That = {
// It appears we can't call map() on `a`.
val keyed_a = mutable.Buffer[(K, A)]()
a.foreach { x => keyed_a += ((key1fn(x), x)) }
val keyed_b = b.map { x => (key2fn(x), x) }
// Nor can we return the value of map() here. Need to use a builder
// instead.
val bu = bf()
for ((_, r) <- keyed_a.intersectWith(keyed_b)(combine))
bu += r
bu.result
}
/**
* Intersect two collections by their keys. Keep the ordering of
* objects in the first collection. Use a combiner function to
* combine items in common. If either item is a multi-map, then
* for a key seen `n` times in the first collection and `m`
* times in the second collection, it will occur `n * m` times
* in the resulting collection, including all the possible
* combinations of pairs of identical keys in the two collections.
*
* #param b Other collection to intersect with.
* #param keyfn Function to select the comparison key.
* #param combine Function to combine values from the two collections.
*/
def intersectBy[K, B >: A, That](b: GenTraversable[B])(keyfn: B => K)(
combine: (A, B) => B)(
implicit bf: CanBuildFrom[Repr, B, That]): That = {
val keyed_a = mutable.Buffer[(K, A)]()
a.foreach { x => keyed_a += ((keyfn(x), x)) }
val keyed_b = b.map { x => (keyfn(x), x) }
val bu = bf()
for ((_, r) <- keyed_a.intersectWith(keyed_b)(combine))
bu += r
bu.result
}
}
I'm not completely sure why just calling map on a GenTraversableLike doesn't seem to work, but so be it.

Liftweb - Convert List[Box[T]] into Box[List[T]]

I would like to convert a List[Box[T]] into a Box[List[T]].
I know that I could use foldRight, but I can't find an elegant way into doing so.
EDIT I would like to keep the properties of Box, that is to say, if there is any failure, return a Box with this failure.
If you only want to collect the "Full" values
I'm not sure why you'd want a Box[List[T]], because the empty list should suffice to signal the lack of any values. I'll assume that's good enough for you.
I don't have a copy of Lift handy, but I know that Box is inspired by Option and has a flatMap method, so:
Long form:
for {
box <- list
value <- box
} yield value
Shorter form:
list.flatMap(identity)
Shortest form:
list.flatten
If you want to collect the failures too:
Here's the mapSplit function I use for this kind of problem. You can easily adapt it to use Box instead of Either:
/**
* Splits the input list into a list of B's and a list of C's, depending on which type of value the mapper function returns.
*/
def mapSplit[A,B,C](in: Traversable[A])(mapper: (A) ⇒ Either[B,C]): (Seq[B], Seq[C]) = {
#tailrec
def mapSplit0(in: Traversable[A], bs: Vector[B], cs: Vector[C]): (Seq[B], Seq[C]) = {
in match {
case t if t.nonEmpty ⇒
val a = t.head
val as = t.tail
mapper(a) match {
case Left(b) ⇒ mapSplit0(as, bs :+ b, cs )
case Right(c) ⇒ mapSplit0(as, bs, cs :+ c)
}
case t ⇒
(bs, cs)
}
}
mapSplit0(in, Vector[B](), Vector[C]())
}
And when I just want to split something that's already a Seq[Either[A,B]], I use this:
/**
* Splits a List[Either[A,B]] into a List[A] from the lefts and a List[B] from the rights.
* A degenerate form of {#link #mapSplit}.
*/
def splitEither[A,B](in: Traversable[Either[A,B]]): (Seq[A], Seq[B]) = mapSplit(in)(identity)
It's really easier to do this with a tail-recursive function than with a fold:
final def flip[T](l: List[Option[T]], found: List[T] = Nil): Option[List[T]] = l match {
case Nil => if (found.isEmpty) None else Some(found.reverse)
case None :: rest => None
case Some(x) :: rest => flip(rest, x :: found)
}
This works as expected:
scala> flip(List(Some(3),Some(5),Some(2)))
res3: Option[List[Int]] = Some(List(3, 5, 2))
scala> flip(List(Some(1),None,Some(-1)))
res4: Option[List[Int]] = None
One can also do this with Iterator.iterate, but it's more awkward and slower, so I would avoid that approach in this case.
(See also my answer in the question 4e6 linked to.)

Cartesian Product and Map Combined in Scala

This is a followup to: Expand a Set of Sets of Strings into Cartesian Product in Scala
The idea is you want to take:
val sets = Set(Set("a","b","c"), Set("1","2"), Set("S","T"))
and get back:
Set("a&1&S", "a&1&T", "a&2&S", ..., "c&2&T")
A general solution is:
def combine[A](f:(A, A) => A)(xs:Iterable[Iterable[A]]) =
xs.reduceLeft { (x, y) => x.view.flatMap {a => y.map(f(a, _)) } }
used as follows:
val expanded = combine{(x:String, y:String) => x + "&" + y}(sets).toSet
Theoretically, there should be a way to take input of type Set[Set[A]] and get back a Set[B]. That is, to convert the type while combining the elements.
An example usage would be to take in sets of strings (as above) and output the lengths of their concatenation. The f function in combine would something of the form:
(a:Int, b:String) => a + b.length
I was not able to come up with an implementation. Does anyone have an answer?
If you really want your combiner function to do the mapping, you can use a fold but as Craig pointed out you'll have to provide a seed value:
def combine[A, B](f: B => A => B, zero: B)(xs: Iterable[Iterable[A]]) =
xs.foldLeft(Iterable(zero)) {
(x, y) => x.view flatMap { y map f(_) }
}
The fact that you need such a seed value follows from the combiner/mapper function type (B, A) => B (or, as a curried function, B => A => B). Clearly, to map the first A you encounter, you're going to need to supply a B.
You can make it somewhat simpler for callers by using a Zero type class:
trait Zero[T] {
def zero: T
}
object Zero {
implicit object IntHasZero extends Zero[Int] {
val zero = 0
}
// ... etc ...
}
Then the combine method can be defined as:
def combine[A, B : Zero](f: B => A => B)(xs: Iterable[Iterable[A]]) =
xs.foldLeft(Iterable(implicitly[Zero[B]].zero)) {
(x, y) => x.view flatMap { y map f(_) }
}
Usage:
combine((b: Int) => (a: String) => b + a.length)(sets)
Scalaz provides a Zero type class, along with a lot of other goodies for functional programming.
The problem that you're running into is that reduce(Left|Right) takes a function (A, A) => A which doesn't allow you to change the type. You want something more like foldLeft which takes (B, A) ⇒ B, allowing you to accumulate an output of a different type. folds need a seed value though, which can't be an empty collection here. You'd need to take xs apart into a head and tail, map the head iterable to be Iterable[B], and then call foldLeft with the mapped head, the tail, and some function (B, A) => B. That seems like more trouble than it's worth though, so I'd just do all the mapping up front.
def combine[A, B](f: (B, B) => B)(g: (A) => B)(xs:Iterable[Iterable[A]]) =
xs.map(_.map(g)).reduceLeft { (x, y) => x.view.flatMap {a => y.map(f(a, _)) } }
val sets = Set(Set(1, 2, 3), Set(3, 4), Set(5, 6, 7))
val expanded = combine{(x: String, y: String) => x + "&" + y}{(i: Int) => i.toString}(sets).toSet

What type to use to store an in-memory mutable data table in Scala?

Each time a function is called, if it's result for a given set of argument values is not yet memoized I'd like to put the result into an in-memory table. One column is meant to store a result, others to store arguments values.
How do I best implement this? Arguments are of diverse types, including some enums.
In C# I'd generally use DataTable. Is there an equivalent in Scala?
You could use a mutable.Map[TupleN[A1, A2, ..., AN], R] , or if memory is a concern, a WeakHashMap[1]. The definitions below (built on the memoization code from michid's blog) allow you to easily memoize functions with multiple arguments. For example:
import Memoize._
def reallySlowFn(i: Int, s: String): Int = {
Thread.sleep(3000)
i + s.length
}
val memoizedSlowFn = memoize(reallySlowFn _)
memoizedSlowFn(1, "abc") // returns 4 after about 3 seconds
memoizedSlowFn(1, "abc") // returns 4 almost instantly
Definitions:
/**
* A memoized unary function.
*
* #param f A unary function to memoize
* #param [T] the argument type
* #param [R] the return type
*/
class Memoize1[-T, +R](f: T => R) extends (T => R) {
import scala.collection.mutable
// map that stores (argument, result) pairs
private[this] val vals = mutable.Map.empty[T, R]
// Given an argument x,
// If vals contains x return vals(x).
// Otherwise, update vals so that vals(x) == f(x) and return f(x).
def apply(x: T): R = vals getOrElseUpdate (x, f(x))
}
object Memoize {
/**
* Memoize a unary (single-argument) function.
*
* #param f the unary function to memoize
*/
def memoize[T, R](f: T => R): (T => R) = new Memoize1(f)
/**
* Memoize a binary (two-argument) function.
*
* #param f the binary function to memoize
*
* This works by turning a function that takes two arguments of type
* T1 and T2 into a function that takes a single argument of type
* (T1, T2), memoizing that "tupled" function, then "untupling" the
* memoized function.
*/
def memoize[T1, T2, R](f: (T1, T2) => R): ((T1, T2) => R) =
Function.untupled(memoize(f.tupled))
/**
* Memoize a ternary (three-argument) function.
*
* #param f the ternary function to memoize
*/
def memoize[T1, T2, T3, R](f: (T1, T2, T3) => R): ((T1, T2, T3) => R) =
Function.untupled(memoize(f.tupled))
// ... more memoize methods for higher-arity functions ...
/**
* Fixed-point combinator (for memoizing recursive functions).
*/
def Y[T, R](f: (T => R) => T => R): (T => R) = {
lazy val yf: (T => R) = memoize(f(yf)(_))
yf
}
}
The fixed-point combinator (Memoize.Y) makes it possible to memoize recursive functions:
val fib: BigInt => BigInt = {
def fibRec(f: BigInt => BigInt)(n: BigInt): BigInt = {
if (n == 0) 1
else if (n == 1) 1
else (f(n-1) + f(n-2))
}
Memoize.Y(fibRec)
}
[1] WeakHashMap does not work well as a cache. See http://www.codeinstructions.com/2008/09/weakhashmap-is-not-cache-understanding.html and this related question.
The version suggested by anovstrup using a mutable Map is basically the same as in C#, and therefore easy to use.
But if you want you can also use a more functional style as well. It uses immutable maps, which act as a kind of accumalator. Having Tuples (instead of Int in the example) as keys works exactly as in the mutable case.
def fib(n:Int) = fibM(n, Map(0->1, 1->1))._1
def fibM(n:Int, m:Map[Int,Int]):(Int,Map[Int,Int]) = m.get(n) match {
case Some(f) => (f, m)
case None => val (f_1,m1) = fibM(n-1,m)
val (f_2,m2) = fibM(n-2,m1)
val f = f_1+f_2
(f, m2 + (n -> f))
}
Of course this is a little bit more complicated, but a useful technique to know (note that the code above aims for clarity, not for speed).
Being a newbie in this subject, I could fully understand none of the examples given (but would like to thank anyway). Respectfully, I'd present my own solution for the case some one comes here having a same level and same problem. I think my code can be crystal clear for anybody having just the very-very basic Scala knowledge.
def MyFunction(dt : DateTime, param : Int) : Double
{
val argsTuple = (dt, param)
if(Memo.contains(argsTuple)) Memo(argsTuple) else Memoize(dt, param, MyRawFunction(dt, param))
}
def MyRawFunction(dt : DateTime, param : Int) : Double
{
1.0 // A heavy calculation/querying here
}
def Memoize(dt : DateTime, param : Int, result : Double) : Double
{
Memo += (dt, param) -> result
result
}
val Memo = new scala.collection.mutable.HashMap[(DateTime, Int), Double]
Works perfectly. I'd appreciate critique If I've missed something.
When using mutable map for memoization, one shall keep in mind that this would cause typical concurrency problems, e.g. doing a get when a write has not completed yet. However, thread-safe attemp of memoization suggests to do so it's of little value if not none.
The following thread-safe code creates a memoized fibonacci function, initiates a couple of threads (named from 'a' through to 'd') that make calls to it. Try the code a couple of times (in REPL), one can easily see f(2) set gets printed more than once. This means a thread A has initiated the calculation of f(2) but Thread B has totally no idea of it and starts its own copy of calculation. Such ignorance is so pervasive at the constructing phase of the cache, because all threads see no sub solution established and would enter the else clause.
object ScalaMemoizationMultithread {
// do not use case class as there is a mutable member here
class Memo[-T, +R](f: T => R) extends (T => R) {
// don't even know what would happen if immutable.Map used in a multithreading context
private[this] val cache = new java.util.concurrent.ConcurrentHashMap[T, R]
def apply(x: T): R =
// no synchronized needed as there is no removal during memoization
if (cache containsKey x) {
Console.println(Thread.currentThread().getName() + ": f(" + x + ") get")
cache.get(x)
} else {
val res = f(x)
Console.println(Thread.currentThread().getName() + ": f(" + x + ") set")
cache.putIfAbsent(x, res) // atomic
res
}
}
object Memo {
def apply[T, R](f: T => R): T => R = new Memo(f)
def Y[T, R](F: (T => R) => T => R): T => R = {
lazy val yf: T => R = Memo(F(yf)(_))
yf
}
}
val fibonacci: Int => BigInt = {
def fiboF(f: Int => BigInt)(n: Int): BigInt = {
if (n <= 0) 1
else if (n == 1) 1
else f(n - 1) + f(n - 2)
}
Memo.Y(fiboF)
}
def main(args: Array[String]) = {
('a' to 'd').foreach(ch =>
new Thread(new Runnable() {
def run() {
import scala.util.Random
val rand = new Random
(1 to 2).foreach(_ => {
Thread.currentThread().setName("Thread " + ch)
fibonacci(5)
})
}
}).start)
}
}
In addition to Landei's answer, I also want to suggest the bottom-up (non-memoization) way of doing DP in Scala is possible, and the core idea is to use foldLeft(s).
Example for computing Fibonacci numbers
def fibo(n: Int) = (1 to n).foldLeft((0, 1)) {
(acc, i) => (acc._2, acc._1 + acc._2)
}._1
Example for longest increasing subsequence
def longestIncrSubseq[T](xs: List[T])(implicit ord: Ordering[T]) = {
xs.foldLeft(List[(Int, List[T])]()) {
(memo, x) =>
if (memo.isEmpty) List((1, List(x)))
else {
val resultIfEndsAtCurr = (memo, xs).zipped map {
(tp, y) =>
val len = tp._1
val seq = tp._2
if (ord.lteq(y, x)) { // current is greater than the previous end
(len + 1, x :: seq) // reversely recorded to avoid O(n)
} else {
(1, List(x)) // start over
}
}
memo :+ resultIfEndsAtCurr.maxBy(_._1)
}
}.maxBy(_._1)._2.reverse
}