Scala 作业记录 00
来源:互联网 发布:java 事物的特征 编辑:程序博客网 时间:2024/06/04 21:36
Functional Programming Principles in Scala
Example Assignment: Instructions
package exampleimport common._object Lists { /** * This method computes the sum of all elements in the list xs. There are * multiple techniques that can be used for implementing this method, and * you will learn during the class. * * For this example assignment you can use the following methods in class * `List`: * * - `xs.isEmpty: Boolean` returns `true` if the list `xs` is empty * - `xs.head: Int` returns the head element of the list `xs`. If the list * is empty an exception is thrown * - `xs.tail: List[Int]` returns the tail of the list `xs`, i.e. the the * list `xs` without its `head` element * * ''Hint:'' instead of writing a `for` or `while` loop, think of a recursive * solution. * * @param xs A list of natural numbers * @return The sum of all elements in `xs` */ def sum(xs: List[Int]): Int = { if (xs.isEmpty) 0 def loop(acc: Int, rem: List[Int]): Int = { if (rem.isEmpty) acc else loop(acc + rem.head, rem.tail) } loop(xs.head, xs.tail) } /** * This method returns the largest element in a list of integers. If the * list `xs` is empty it throws a `java.util.NoSuchElementException`. * * You can use the same methods of the class `List` as mentioned above. * * ''Hint:'' Again, think of a recursive solution instead of using looping * constructs. You might need to define an auxiliary method. * * @param xs A list of natural numbers * @return The largest element in `xs` * @throws java.util.NoSuchElementException if `xs` is an empty list */ def max(xs: List[Int]): Int = { if (xs.isEmpty) { throw new java.util.NoSuchElementException } def loop(acc: Int, rem: List[Int]): Int = { if (rem.isEmpty) acc else loop( if (acc > rem.head) acc else rem.head , rem.tail) } loop(xs.head, xs.tail) }}
0 0
- Scala 作业记录 00
- Scala 作业记录 01
- Scala 作业记录 03
- scala记录
- Scala第二天作业
- Scala第三天作业
- scala 第一天作业
- Scala学习记录-Scala是什么
- scala 第一周编程作业
- scala parse使用记录
- Scala学习记录-Scala入门资源
- Scala学习记录-Scala Windows环境搭建
- 算法作业记录
- html作业记录
- Coursera_Stanford_ML_ex1 作业记录
- Coursera_Stanford_ML_ex2_Logistic Regression 作业记录
- UFLDL作业记录
- 偶尔记录的作业
- ubuntu下安装Docker
- eclipse安装找不到jre\bin\client\jvm.dll的问题
- HDU 4908 BestCoder Sequence(组合数学)
- 使用Xming + PuTTY在client端(window) 使用linux图形界面程序
- 关于软引用
- Scala 作业记录 00
- Hadoop2.4.0伪分布安装步骤
- activeX 组件修改 ——提高网络安全性
- Paste
- hdu1087 Super Jumping! Jumping! Jumping!
- Jquery Table 的基本操作
- HDU 4909 String(组合数学)
- 心情实验
- HDOJ 题目3032Nim or not Nim?(sg博弈)