I am trying to reduce the extent to which I write Scala (2.8) as Java. Here's a simplification of the problem I encountered. Can you suggest improvements to my solutions that are “more functional”?
Map conversion
val inputMap = mutable.LinkedHashMap(1->'a',2->'a',3->'b',4->'z',5->'c')
discarding any entries with a value of 'z' and indexing characters when they occur
Try first
var outputMap = new mutable.HashMap[Char,Int]()
var counter = 0
for(kvp <- inputMap){
val character = kvp._2
if(character !='z' && !outputMap.contains(character)){
outputMap += (character -> counter)
counter += 1
}
}
The second attempt (not much better, but uses an immutable map and "foreach")
var outputMap = new immutable.HashMap[Char,Int]()
var counter = 0
inputMap.foreach{
case(number,character) => {
if(character !='z' && !outputMap.contains(character)){
outputMap2 += (character -> counter)
counter += 1
}
}
}
source
share