blue-sky
blue-sky

Reputation: 53826

How to understand function reduceLeft?

Why can (1 :: xs) be inserted? One is cons'd onto beginning of list xs.

So List(3,2,1) becomes List(1,3,2,1) but what is significance of (1 :: xs)?

I'm having trouble understanding how this works :

def product(xs : List[Int]) = (1 :: xs) reduceLeft((x , y) => x * y)

In method signature a prefix operand (in this case (1 :: xs)) is not described? :

def reduceLeft[B >: A](f: (B, A) => B): B =

Upvotes: 0

Views: 168

Answers (3)

Vinicius Miana
Vinicius Miana

Reputation: 2067

(1 :: xs) is not a prefix operand.

You are actually adding 1 before your list xs.

So product(List(3,2,1)) becomes List(1,3,2,1) reduceLeft((x,y) => x * y).

The reduceLeft function will take the 2 elements on the left and replace by the result of your function (x,y) => x * y.

In your case

List(1,3,2,1) => takes (1,3) and replaces by 1* 3 = 3 new List: List(3,2,1)
List(3,2,1) => takes (3,2) and replaces by 3 *2 = 6 new List: (6,1)
Finally takes (6,1) and get the final result 6.

As multiplying by one has no effect in the product, we add the number 1 before the List to avoid an error if the List is Empty.

Remove that and try product(List()) and you will see. If the List had at least on element (1::xs) will have no effect in your function

Upvotes: 2

Kelsey Gilmore-Innis
Kelsey Gilmore-Innis

Reputation: 1010

That's not a prefix operand--it's a method invocation on a List instance. The method reduceLeft is being called on the List (1 :: xs).

(1 :: xs) reduceLeft((x , y) => x * y)

can also be written as

(1 :: xs).reduceLeft((x , y) => x * y)

Or, even more explicitly:

val myList = (1 :: xs)
myList.reduceLeft((x , y) => x * y)

Upvotes: 0

joescii
joescii

Reputation: 6533

I believe you understand cons just fine. (1 :: xs) is simply another way to express List(1,3,2,1), on which you then invoke reduceLeft.

As for a better understanding of reduceLeft, I recently blogged this exact topic.

Upvotes: 0

Related Questions