defsum(list: List[Int]): Int = list.foldLeft(0)((r,c) => r+c)
defsum(list: List[Int]): Int = list.foldLeft(0)(_+_)
defproduct(list: List[Int]): Int = list.foldLeft(1)(_*_)
defcount(list: List[Any]): Int =
list.foldLeft(0)((sum,_) => sum + 1)
defaverage(list: List[Double]): Double =
list.foldLeft(0.0)(_+_) / list.foldLeft(0.0)((r,c) => r+1)
defaverage(list: List[Double]): Double = list match {
case head :: tail => tail.foldLeft( (head,1.0) )((r,c) =>
((r._1 + (c/r._2)) * r._2 / (r._2+1), r._2+1) )._1
case Nil => NaN
}
def last[A](list: List[A]): A =
list.foldLeft[A](list.head)((_, c) => c)
def get[A](list: List[A], idx: Int): A =
list.tail.foldLeft((list.head,0)) {
(r,c) => if (r._2 == idx) r else (c,r._2+1)
} match {
case (result, index) if (idx == index) => result
case _ => thrownewException("Bad index")
}
defmimicToString[A](list: List[A]): String = list match {
case head :: tail => tail.foldLeft("List(" + head)(_ + ", " + _) + ")"
case Nil => "List()"
}
def reverse[A](list: List[A]): List[A] =
list.foldLeft(List[A]())((r,c) => c :: r)
def unique[A](list: List[A]): List[A] =
list.foldLeft(List[A]()) { (r,c) =>
if (r.contains(c)) r else c :: r
}.foldLeft(List[A]())((r,c) => c :: r)
def group[A](list: List[A], size: Int): List[List[A]] =
list.foldLeft( (List[List[A]](),0) ) { (r,c) => r match {
case (head :: tail, num) => if (num < size) ( (c :: head) :: tail , num + 1 ) else ( List(c) :: head :: tail , 1 ) case (Nil, num) => (List(List(c)), 1) }
}._1.foldLeft(List[List[A]]())( (r,c) => c.reverse :: r)