Skip to main content
 首页 » 编程设计

scala coursera 函数式编程作业 FunSets

2025年05月04日132soundcode

我在 coursera 上的 scala 中参加了 martin odersky 的函数式编程类(class)。
但是,我无法理解第二个作业 Funsets.scala 的解决方案。

type Set = Int => Boolean 
 
  /** 
   * Indicates whether a set contains a given element. 
   */ 
  def contains(s: Set, elem: Int): Boolean = s(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 = (e: Int) => s(e) || t(e) 

问题在上面的函数中,什么是e?它从何而来 ?我知道 union 函数结合了这两个集合,但是这里我从方法定义中理解的是,它需要 2 个集合作为输入并返回结果并集,那么 e 是从哪里来的呢?

  /** 
   * Returns the intersection of the two given sets, 
   * the set of all elements that are both in `s` or `t`. 
   */ 
  def intersect(s: Set, t: Set): Set = (e: Int) => s(e) && t(e) 

同样的问题也适用于相交函数。
请任何人解释一下上述两个函数的操作,即这两个语句

(e: Int) => s(e) || t(e)(e: Int) => s(e) && t(e)

请您参考如下方法:

def union(s: Set, t: Set): Set = (e: Int) => s(e) || t(e) 

让我们把它分解成小块。

  • def union()我正在定义一个我将调用的方法 union .
  • (s: Set, t: Set)此方法将采用我将调用的 2 个参数 st , 均为 Set 类型.
  • : Set此方法将返回 Set 类型的值.等等……什么是 Set ?
  • type Set = Int => Boolean啊,好的,Set是一个接受 Int 的函数作为参数并返回 Boolean因此。知道了。返回 union()方法。
  • (e: Int) => s(e) || t(e)这是一个接受 Int 类型的单个参数的函数。 .我将调用该参数 e .当此函数收到 Int它将被馈送到st . st都是类型Set ,这意味着当喂食 Int他们返回 Boolean .那么我们将有 2 个 Boolean值,它们将被或在一起以产生单个 Boolean ,它与 Set 的定义相匹配(Int 输入,Boolean 输出),所以我们完成了。

现在让我们创建一个示例,看看如何使用它。

val setA:Set = x => x == 5   //this Set is true only for 5 
val setB:Set = y => y == 2   //this Set is true only for 2 
val setU = union(setA, setB) //setA is parameter s, setB is parameter t 
 
setU(2)  //'e' is now 2, this returns true 
setU(5)  //'e' is now 5, this returns true 
setU(25) //'e' is now 25, this returns false