Associative array/Creation: Difference between revisions

Added Scala example
mNo edit summary
(Added Scala example)
Line 256:
echo('Key: '.$key.' Value: '.$value);
}
 
==[[Scala]]==
[[Category:Scala]]
// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map.isDefinedAt(33) // false
map.isDefinedAt(44) // true
 
// mutable maps (HashSets)
import scala.collection.mutable.HashMap
val hash = new HashMap[int, int]
hash + (1 -> 2)
hash + (3 -> 4, 5 -> 6, 44 -> 99)
hash(44) // 99
hash.isDefinedAt(33) // false
hash.isDefinedAt(44) // true
 
// iterate over key/value
hash.foreach {k => Console.println("key "+k._1+" value "+k._2)} // k is a 2 element Tuple
 
// remove items where the key is <= 3
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
 
 
==[[Perl]]==
Anonymous user