Hongxu Chen
Hongxu Chen

Reputation: 5350

How to get a Long typed production of a Seq[Int] in Scala?

Suppose val s = Seq[Int] and I would like to get the production of all its elements. The value is guaranteed to be greater than Int.MaxValue but less than Long.MaxValue so I hope the value to be a Long type.

It seems I cannot use product/foldLeft/reduceLeft due to the fact Long and Int are different types without any relations; therefore I need to write a for-loop myself. Is there any decent way to achieve this goal?

Note: I'm just asking the possibility to use builtin libraries but still fine with "ugly" code below.

def product(a: Seq[Int]): Long = {
    var p = 1L
    for (e <- a) p = p * e
    p
  }

Upvotes: 0

Views: 470

Answers (2)

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

There's no need to mess about with asInstanceOf or your own loop. foldLeft works just fine

val xs = Seq(1,1000000000,1000000) 
xs.foldLeft(1L)((a,e) => a*e)
//> res0: Long = 1000000000000000

Upvotes: 4

jamesmulcahy
jamesmulcahy

Reputation: 308

How about

def product(s: Seq[Int]) = s.map(_.asInstanceOf[Long]).fold(1L)( _ * _ )

In fact, having re-read your question and learnt about the existence of product itself, you could just do:

def product(s: Seq[Int]) = s.map(_.asInstanceOf[Long]).product

Upvotes: 1

Related Questions