Lab 4
Lab 4
//Function as Parameter
val salaries = List(20000, 70000, 40000)
val doubleSalary = (x: Int) => x * 1.5
val newSalaries = salaries.map(doubleSalary)
println(newSalaries)
Output: List(30000.0, 105000.0, 60000.0)
Filter
1. The filter allows us to clear a collection from elements we are not
interested in
2. It accepts a predicate
3. This predicate should evaluate to a boolean (true or false)
4. It removes all elements that do not satisfy that predicate
Filter
Output:List(one, two)
Reduce
1. The reduce method is a higher order method that takes all the
elements in a collection (list ,array ,seq..) and combine them using a
binary operation to produce a single value.
2. It necessary to make sure that the operations are commutative and
associative.
3. This Anonymous functions are passed as a parameter to the reduce
function.
4. The result should be of the same type as that of the collection
elements
Reduce
var collection = List(200, val ch = List("A", "B", "C",
400, 100, 30, 1000, 500) "D", "E", "F")
1. The foldleft iterates through the list from left to right, accumulating
elements in that order.
2. FoldLeft is quite similar to reduce
3. The difference is that we can set an initial value for the accumulator
Foldleft
val array = List(1,2,3,4,5)
• You can return that anonymous function from the body of another function
as follows:
def saySomething(prefix: String): String=>String =
(s: String) => {prefix + " " + s}
Return Function
• val sayHello = saySomething("Hello")
• Because saySomething returns a function, you can assign that resulting
function to a variable.
• sayHello(“Ali”)
println(sayHello("Ali”))
Output: Hello Ali
Hands on (Return Function)
• That function will take a string parameter and print it using println.
• p.S : To simplify, greet won’t take any input parameters; it will just
build a function and return it.
Hands on (Return Function)