recursion

Scala: An attempt at recursion

I have been playing with scala on & off for a couple of months. One of the major differences between it and other languages that I use is that it provides immutable data structures (as well as mutable ones). One of the things I am having issues with is working with the immutable structures, they appear to require some understanding of recursion – combined with a lack of intelligence and understanding, this can make life tricky.

Below is a block of code that imports the already imported immutable.collection.Map and then attempts to create an immutable map from a List(Int,String). The result of the code is: Map(1 -> silly, 2 -> code, -1 -> some, 3 -> hacking). This may or may not be the way to do things properly, I haven’t had a chance to read either of my scala books recently.

def populateImmutableMap( aList:List[(Int,String)] ): Map[Int,String] = {
	def subPop( m:Map[Int,String], aListTail:List[(Int,String)]): Map[Int,String] = {
		aListTail match {
			case hd::tail => { subPop(( m ++ Map(aListTail.head._1 -> aListTail.head._2)), aListTail.tail) }
			case Nil => { m }
		}
	}
	subPop( Map(), aList )
}

val someData = List( (1,"silly"),(2,"code"),(-1,"some"),(3,"hacking") )
val m = populateImmutableMap( someData )
println(m)