Is Scala functional programming slower than traditional coding?

前端 未结 9 2086
离开以前
离开以前 2020-12-22 22:23

In one of my first attempts to create functional code, I ran into a performance issue.

I started with a common task - multiply the elements of two arrays and sum up

9条回答
  •  一生所求
    2020-12-22 22:59

    I am not an expert Scala programmer, so there is probably a more efficient method, but what about something like this. This can be tail call optimized, so performance should be OK.

    def multiply_and_sum(l1:List[Int], l2:List[Int], sum:Int):Int = {
        if (l1 != Nil && l2 != Nil) {
            multiply_and_sum(l1.tail, l2.tail, sum + (l1.head * l2.head))
        }
        else {
            sum
        }
    }
    
    val first = Array(1,2,3,4,5)
    val second = Array(6,7,8,9,10)
    multiply_and_sum(first.toList, second.toList, 0)  //Returns: 130
    

提交回复
热议问题