Apply a callback to an array: Difference between revisions
Content added Content deleted
(→{{header|FP}}: Changed compiler link to internal link) |
|||
Line 556: | Line 556: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
val l = List(1,2,3,4) |
val l = List(1,2,3,4) |
||
l.foreach {i => |
l.foreach {i => println(i)} |
||
When the argument appears only once -as here, i appears only one in println(i) - it may be shortened to |
|||
l.foreach(println(_)) |
|||
Same for an array |
Same for an array |
||
val a = Array(1,2,3,4) |
val a = Array(1,2,3,4) |
||
a.foreach {i => |
a.foreach {i => println(i)} |
||
a.foreach(println(_)) '' // same as previous line'' |
|||
Or for an externally defined function : |
|||
def doSomething(in: int) = { |
def doSomething(in: int) = {println("Doing something with "+in)} |
||
l.foreach(doSomething) |
l.foreach(doSomething) |
||
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be define on ''a'' |
There is also a ''for'' syntax, which is internally rewritten to call foreach. A foreach method must be define on ''a'' |
||
for(val i <- a) |
for(val i <- a) println(i) |
||
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections) |
It is also possible to apply a function on each item of an list to get a new list (same on array and most collections) |
||
val squares = l.map{i => i * i} // |
val squares = l.map{i => i * i} ''//squares is'' List(1,4,9,16) |
||
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach |
Or the equivalent ''for'' syntax, with the additional keyword ''yield'', map is called instead of foreach |