Scala List foldLeft用法
来源:互联网 发布:淘宝设置发货地 编辑:程序博客网 时间:2024/06/04 08:28
def sum(list: List[Int]): Int = list.foldLeft(0)((r,c) => r+c)def sum(list: List[Int]): Int = list.foldLeft(0)(_+_)
def product(list: List[Int]): Int = list.foldLeft(1)(_*_)
def count(list: List[Any]): Int = list.foldLeft(0)((sum,_) => sum + 1)
def average(list: List[Double]): Double = list.foldLeft(0.0)(_+_) / list.foldLeft(0.0)((r,c) => r+1)def average(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 _ => throw new Exception("Bad index")}
def mimicToString[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)
0 0
- Scala List foldLeft用法
- scala学习之:List的foldLeft、foldRight操作实战
- scala-37::List的foldLeft、foldRight、sort操作代码实战
- 【Scala】通过【foldLeft】来判断一个List是否是另一个List的子集
- Scala深入浅出实战经典:37,List的foldLeft、foldRight、sort操作代码实战
- Scala的foldLeft和foldRight
- Scala的foldLeft和foldRight
- Scala的foldLeft和foldRight
- Scala: foldLeft和foldRight 实战
- Scala :foldLeft foldRight min max
- scala里面的foldLeft和foldRight
- Secret powers of foldLeft() in Scala
- scala基础38-foldLeft/foldRight/sortWith
- scala中的reduceLeft,reduceRight,foldLeft,foldRight方法
- scala List集合的用法
- scala List集合的用法
- Scala:fold,foldLeft和foldRight区别与联系
- Scala:fold,foldLeft和foldRight区别与联系
- 第2周项目1-旱冰场造价
- SELLYA OPENCART 商城自适应主题模板 ABC-0011-07
- C语言,数的表示(整数)
- Cocos2d-JS开发中的一些小技巧
- Ubuntu14.04 安装ibus-googlepinyin方法介绍
- Scala List foldLeft用法
- JMM导读
- Eclipse Java注释模板设置详解
- html块状元素和行内元素
- #个人赛第一场解题总结#
- COM组件学习笔记--C++模板
- KNN算法实现手写识别系统
- P27 6
- 在win7下优盘安装ubuntu组成双系统,多图。。。