2017-12-16 15 views
1

Scalaの型システムにはあまりよく慣れていませんが、ここで私がしようとしていることがあります。Scalaのコンテナ代数データ型

私は姓と名で人をフィルタリングしようとする機能を持っていますが、それが最初の名前だけでフィルタに失敗するとします。

case class Person(id: Int, first: String, last:String) 
def(people: Set[Person], firstName: String, lastName: String): (MatchResult, Set[Person]) = 
    val (both, firstOnly) = people.filter(_.first == firstName).partition(_.last == lastName) 

    (both.nonEmpty, firstOnly.nonEmpty) match { 
    case (true, _) => (BothMatch, both) 
    case (false, true) => (FirstOnly, firstOnly) 
    case (_, _) => (NoMatch, Set[Person]()) 
    } 

は、今私は、フィルタの結果を使用した発信者を知らせる代数的データ型と一緒にフィルタリングSetを返しています。

sealed trait MatchResult 
case object BothMatch extends MatchResult 
case object FirstOnly extends MatchResult 
case object NoMatch extends MatchResult 

しかし、呼び出し側のための非常に素晴らしい契約を提示していないSet + MatchResultのタプルを返します。私はフィルタリングされた結果をどのように保存することができますか私のMatchResult

は、私は単にに変えることができると思った:

sealed trait MatchResult extends Set[People] 
case object BothMatch extends MatchResult 
case object FirstOnly extends MatchResult 
case object NoMatch extends MatchResult 

しかし、コンパイラは、私はSetを延長するか、何とかMatchResultcase classを作ってみる必要がある場合、私はmust implement abstract member iterator: Iterator[A]

私はよく分からないことを私に伝えていますコンストラクタ引数としてセットを受け取ります。

答えて

3

1つの方法は、一致をメンバーとして格納するためにケースクラスを使用することです。

sealed trait MatchResult 
case class BothMatch(results:Set[Person]) extends MatchResult 
case class FirstOnly(results:Set[Person]) extends MatchResult 
case object NoMatch extends MatchResult 
Scalaで

、任意の実装クラスによって実装されなければならないSet is is trait that has abstract members、そしてあなたがそのエラーを受けている理由です。あなたの実装で

、あなたが

(both.nonEmpty, firstOnly.nonEmpty) match { 
    case (true, _) => BothMatch(both) 
    case (false, true) => FirstOnly(firstOnly) 
    case (_, _) => NoMatch 
    } 
+0

これは私が必要なものを正確である、ことでこれらのクラスを使用することができます - あなたに感謝! – diplosaurus

関連する問題