セット s1 {1, 2} の非常に単純な例があり、それに述語 p > 1 を適用したいと考えています。今、私はこの機能を実装しましたが、正しい結果が得られています。
def filter(s: Set, p: Int => Boolean): Set = {(i: Int) => s(i) && p(i)}
セットの定義はどこですか
type Set = Int => Boolean
しかし、Scala でそれを行うよりエレガントな方法はありますか?
セット s1 {1, 2} の非常に単純な例があり、それに述語 p > 1 を適用したいと考えています。今、私はこの機能を実装しましたが、正しい結果が得られています。
def filter(s: Set, p: Int => Boolean): Set = {(i: Int) => s(i) && p(i)}
セットの定義はどこですか
type Set = Int => Boolean
しかし、Scala でそれを行うよりエレガントな方法はありますか?
このコースの 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 の実装は省略しました。