Functional Programming Principles in Scala 
by Martin Odersky

这一周的主要内容是函数。函数是scala语言最重要的概念,既可以当作函数的参数,也可以作为返回值。函数还可以拥有多个参数列表。

因此,这次作业就是要把函数作为参数和返回值,实现set数据类型的一些方法。而set本身却是一个函数,这一点非常奇妙。另外测试程序也要自己实现。

编程过程中,发现有些函数实现的方法非常复杂,不知道是否有简化的方法。

作业要求如下:

In this assignment, you will work with a functional representation of sets based on the mathematical notion of characteristic functions. The goal is to gain practice with higher-order functions.Download the funsets.zip handout archive file and extract it somewhere on your machine. Write your solutions by completing the stubs in the FunSets.scala file.Write your own tests! For this assignment, we don’t give you tests but instead the FunSetSuite.scala file contains hints on how to write your own tests for the assignment.Representation
We will work with sets of integers.As an example to motivate our representation, how would you represent the set of all negative integers? You cannot list them all… one way would be so say: if you give me an integer, I can tell you whether it’s in the set or not: for 3, I say ‘no’; for -1, I say yes.Mathematically, we call the function which takes an integer as argument and which returns a boolean indicating whether the given integer belongs to a set, the characteristic function of the set. For example, we can characterize the set of negative integers by the characteristic function (x: Int) => x < 0.Therefore, we choose to represent a set by its characterisitc function and define a type alias for this representation:type Set = Int => Boolean
Using this representation, we define a function that tests for the presence of a value in a set:def contains(s: Set, elem: Int): Boolean = s(elem)
2.1 Basic Functions on Sets
Let’s start by implementing basic functions on sets.Define a function which creates a singleton set from one integer value: the set represents the set of the one given element. Its signature is as follows:def singletonSet(elem: Int): Set
Now that we have a way to create singleton sets, we want to define a function that allow us to build bigger sets from smaller ones.Define the functions union, intersect, and diff, which takes two sets, and return, respectively, their union, intersection and differences. diff(s, t) returns a set which contains all the elements of the set s that are not in the set t. These functions have the following signatures:def union(s: Set, t: Set): Set
def intersect(s: Set, t: Set): Set
def diff(s: Set, t: Set): Set
Define the function filter which selects only the elements of a set that are accepted by a given predicate p. The filtered elements are returned as a new set. The signature of filter is as follows:def filter(s: Set, p: Int => Boolean): Set
2.2 Queries and Transformations on Sets
In this part, we are interested in functions used to make requests on elements of a set. The first function tests whether a given predicate is true for all elements of the set. This forall function has the following signature:def forall(s: Set, p: Int => Boolean): Boolean
Note that there is no direct way to find which elements are in a set. contains only allows to know whether a given element is included. Thus, if we wish to do something to all elements of a set, then we have to iterate over all integers, testing each time whether it is included in the set, and if so, to do something with it. Here, we consider that an integer x has the property -1000 <= x <= 1000 in order to limit the search space.Implement forall using linear recursion. For this, use a helper function nested in forall. Its structure is as follows (replace the ???):def forall(s: Set, p: Int => Boolean): Boolean = {def iter(a: Int): Boolean = {if (???) ???else if (???) ???else iter(???)}iter(???)
}Using forall, implement a function exists which tests whether a set contains at least one element for which the given predicate is true. Note that the functions forall and exists behave like the universal and existential quantifiers of first-order logic.def exists(s: Set, p: Int => Boolean): Boolean
Finally, write a function map which transforms a given set into another one by applying to each of its elements the given function. map has the following signature:def map(s: Set, f: Int => Int): Set
Extra Hints
Be attentive in the video lectures on how to write anonymous functions in Scala.
Sets are represented as functions. Think about what it means for an element to belong to a set, in terms of function evaluation. For example, how do you represent a set that contains all numbers between 1 and 100?
Most of the solutions for this assignment can be written as one-liners. If you have more, you probably need to rethink your solution. In other words, this assignment needs more thinking (whiteboard, pen and paper) than coding ;-).
If you are having some trouble with terminology, have a look at the glossary.

实现的程序如下:

package funsetsimport common._/*** 2. Purely Functional Sets.*/
object FunSets {/*** We represent a set by its characteristic function, i.e.* its `contains` predicate.*/type Set = Int => Boolean/*** Indicates whether a set contains a given element.*/def contains(s: Set, elem: Int): Boolean = s(elem)/*** Returns the set of the one given element.*/def singletonSet(elem: Int): Set = x=>x==elem/*** Returns the union of the two given sets,* the sets of all elements that are in either `s` or `t`.*/def union(s: Set, t: Set): Set = x=>s(x) || t(x)/*** Returns the intersection of the two given sets,* the set of all elements that are both in `s` and `t`.*/def intersect(s: Set, t: Set): Set = x=>s(x) && t(x)/*** Returns the difference of the two given sets,* the set of all elements of `s` that are not in `t`.*/def diff(s: Set, t: Set): Set = x=>s(x) && (!t(x))/*** Returns the subset of `s` for which `p` holds.*/def filter(s: Set, p: Int => Boolean): Set = x=> s(x) && p(x)/*** The bounds for `forall` and `exists` are +/- 1000.*/val bound = 1000/*** Returns whether all bounded integers within `s` satisfy `p`.*/def forall(s: Set, p: Int => Boolean): Boolean = {def iter(a: Int): Boolean = {if (a== -bound-1) trueelse if (s(a) && !p(a)) falseelse iter(a-1)}iter(bound)}/*** Returns whether there exists a bounded integer within `s`* that satisfies `p`.*/def exists(s: Set, p: Int => Boolean): Boolean = ! forall(s, x => !p(x))/*** Returns a set transformed by applying `f` to each element of `s`.*/def map(s: Set, f: Int => Int): Set = x=>exists(s,elem=>f(elem)==x)/*** Displays the contents of a set*/def toString(s: Set): String = {val xs = for (i <- -bound to bound if contains(s, i)) yield ixs.mkString("{", ",", "}")}/*** Prints the contents of a set on the console.*/def printSet(s: Set) {println(toString(s))}
}

测试部分代码片段如下:

  test("union contains all elements") {new TestSets {val s = union(s1, s2)assert(contains(s, 1), "Union 1")assert(contains(s, 2), "Union 2")assert(!contains(s, 3), "Union 3")}}test("union intersect diff"){def a(x:Int)= x<20def b(x:Int)= x>10assert(contains(union(a,b), 55), "Union")assert(contains(union(a,b), 5), "Union")assert(contains(intersect(a,b), 15), "intersect")assert(!contains(diff(a,b), 15), "diff")assert(contains(diff(a,b), 5), "diff")}test("forall exists map"){def a(x:Int)=x<10assert(forall(a,x=>x*x>=0),"forall")assert(!forall(a,x=>x*x<60),"forall")assert(exists(a,x=>x*10==50),"exists")assert(!exists(a,x=>x*10==120),"exists")assert(contains(map(a,x=>x*x),64),"contains")assert(!contains(map(a,x=>x*x),640),"contains")}

Martin Odersky Scala编程公开课 第二周作业相关推荐

  1. Martin Odersky Scala编程公开课 第一周作业

    Functional Programming Principles in Scala  by Martin Odersky Martin教授是scala语言的creator,在coursera上面有s ...

  2. Martin Odersky Scala编程公开课 第三周作业

    Functional Programming Principles in Scala  by Martin Odersky 这次的作业叫做Object-Oriented Sets.要完成一个完整的类, ...

  3. 神经网络思想建立LR模型(DL公开课第二周答案)

    上海站 | 高性能计算之GPU CUDA培训 4月13-15日 三天密集式学习  快速带你晋级 阅读全文 > 正文共6603个字,3张图,预计阅读时间17分钟. LR回顾 LR计算图求导 算法结 ...

  4. 【编译原理】 CS143 斯坦福大学公开课 第二周:词法分析和有限自动机(下)

    youtube :词法规则 文章较长,是4节视频的合集,大家看的时候多思考吧. 4.1| Lexical Specification – 词法规则 回顾: 如何识别任意字符串是否属于某一语言? 步骤: ...

  5. 高级编程技术 Python 第二周作业

    本周主要内容为列表和元组的基本操作. 一.教材第三章练习选做 3-1.3-2:基本的列表使用,没有任何难度. #3-1, 3-2 names = ['Okabe Rintaro', 'Makise K ...

  6. SAP Fiori Elements 公开课第二单元视频的台词和课程主要内容

    课程地址 很多 SAP 从业者反映,open SAP 上的视频,因为网络原因无法访问,所以我会陆续在我的个人微 信 号"汪子熙"上面,把这些视频配上中文字幕并发布出来,敬请关注. ...

  7. 20172307 结对编程项目-四则运算 第二周 阶段总结

    20172307 结对编程项目-四则运算 第二周 阶段总结 (结队项目码云地址) 相关过程截图(关键代码处加了注释) 编写出实现中缀转后缀的类Transform /*Transform.java 作者 ...

  8. “悟道”公开课第二讲丨如何优化大模型输出结果

    图片出处:https://bmk.sh/2020/05/29/GPT-3-A-Brief-Summary/ 如果你错过了上一波深度学习引发的NLP范式转换,不要再错过这一波超大预训练模型的崛起. 现在 ...

  9. 【中文】【吴恩达课后编程作业】Course 4 - 卷积神经网络 - 第二周作业

    [中文][吴恩达课后编程作业]Course 4 - 卷积神经网络 - 第二周作业 - Keras入门与残差网络的搭建 上一篇:[课程4 - 第二周测验]※※※※※ [回到目录]※※※※※下一篇:[课程 ...

最新文章

  1. reid 数据集 行人重拾别
  2. SDN和SD-WAN有本质区别—Vecloud微云
  3. 神策数据 × 水滴汽车:着眼车主忠诚度,实现转型期逆势增长!
  4. uva 11992 - Fast Matrix Operations
  5. asp.net core 6 新特性,支持HTTP/3 端点发布
  6. iOS 推送功能打包后获取不到deviceToken
  7. Proteus8.6 安装教程
  8. 关于SMP IRQ affinity
  9. S7-1200使用集成库FB285控制G120变频器的基本步骤
  10. GO中时间转换到毫秒
  11. 大学计算机基础网络应用第二套,大学计算机基础)应用指导(第2版
  12. Android ListView点击之后保持更换的背景色,实现已读功能
  13. 3D NAND 前沿
  14. 成为智者的四个敌人——唐望
  15. 操作系统——文件管理实验
  16. Delphi中record的使用
  17. PPT打印省纸法及改变ppt背景
  18. < Linux >:Linux 进程概念 (1)
  19. 电脑里的计算机无法打字,电脑键盘无法打字的原因及解决方案
  20. NAT 2 - 利用Rotary NAT实现TCP流量负载均衡 [译] + GNS3实现

热门文章

  1. Spark Shuffle系列-----1. Spark Shuffle与任务调度之间的关系
  2. vc6下usb编程_5款免费的C/C++语言编程器
  3. 光电显示未连接服务器,T106串口服务器解决方案
  4. 简述python在量化金融中应用_Python金融与量化投资分析应用
  5. dubbo 支持服务降级吗_关于dubbo的服务降级
  6. java 8 两个list_java集合框架综述
  7. python中metaclass的理解
  8. ccs4c语言用户手册,CCS v4.x快速入门:EasyDsp开发套件产品手册
  9. linux脚本实现多重管道,制作Linux shell时流重定向和管道
  10. 同名字的数值求和插入行_SUM求和函数的运用,这些EXCEL表格技能你必须知道,让你事半功倍...