Сообщения

Изображение
In functional programming, functions can be assigned to variables, passed to other functions as parameters, and returned as values from other functions. Such functions are known as First Class Functions. A higher-order function is a function which takes a function as argument or returns a function. Examples: object HOFuncs extends App { def sum(f: Int => Int, a: Int, b: Int):Int = { if (a > b) 0 else f(a)+sum(f,a+1,b) } def sq(x: Int) : Int = x*x def cube(x: Int) : Int = x*x*x def usrFun(x: Int) :Int = x + x*x println("sum(sq,1,3) = "+sum(sq,1,3)) // 1*1 + 2*2 + 3*3 = 1+4+9 = 14 println("sum(cube,1,3) = "+sum(cube,1,3)) // 1+8+27 = 36 println("sum(usrFun,1,3) = "+sum(usrFun,1,3)) // (1+1*1)+(2+2*2)+(3+3*3) = 2 + 6 + 12 = 20 } Output: sum(sq,1,3) = 14 sum(cube,1,3) = 36 sum(usrFun,1,3) = 20 Now I am going calculate integral of function of one variable with mathematics and with scala. Als...

Seq of Tuples

Search tuple in sequence of tuples where second element has maximum for all sequence. object CollectStudy extends App { val seqTup = Seq((1,1), (2,3), (3,5), (4,8), (5,7), (6,5), (7,3), (8,1) ,(9,8)) println(seqTup) // solution 1 val elmMax = seqTup(seqTup.map(x => x._2).indexOf(seqTup.map(y => y._2).max)) println(elmMax) //solution 2 val seqVals = seqTup.map(x => x._2) val maxVal = seqVals.max val idxMax = seqVals.indexOf(maxVal) val elm2Max = seqTup(idxMax) println(elm2Max) //solution 3 - get all maximums val elmMax = seqTup.filter{_._2 == (seqTup.map(y => y._2).max)} println(elmMax) } Output is List((1,1), (2,3), (3,5), (4,8), (5,7), (6,5), (7,3), (8,1), (9,8)) (4,8) (4,8) List((4,8), (9,8))