0

セット s1 {1, 2} の非常に単純な例があり、それに述語 p > 1 を適用したいと考えています。今、私はこの機能を実装しましたが、正しい結果が得られています。

  def filter(s: Set, p: Int => Boolean): Set = {(i: Int) => s(i) && p(i)}

セットの定義はどこですか

  type Set = Int => Boolean

しかし、Scala でそれを行うよりエレガントな方法はありますか?

4

1 に答える 1

5

このコースの a の定義を使用するSetと、あなたの答えは非常に洗練されたものになります。

述語は実際にはSetあまりにもa であるため、関数filterを再利用することではるかに簡潔になる可能性があります。intersect

/**
 * 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 = ???

/**
 * Returns the subset of `s` for which `p` holds.
 */
def filter(s: Set, p: Int => Boolean): Set = intersect(s, p)

Coursera 倫理規定により課題の回答を共有できないため、intersect の実装は省略しました。

于 2013-10-06T21:07:53.373 に答える