2017-01-23 15 views
1

これは化粧用のScalaの質問の一種です。オブジェクトのリストは、オブジェクトの属性でフィルタリングする必要があります。属性の最初のチェックが空のリストになるかどうかを報告する必要があります。簡体字コード:もちろん複数の述語をフィルタリングして報告する

case class Account (id: Int, balance: Float) 

def doFilter(list: List[Account], focusId: Int, thresHold: Float): List[Account] = { 
    list.filter(_.id == focusId) 
    // ## if at this point if the list is empty, an error log is required. 
    .filter(_.balance >= thresHold) 
} 

var accounts = List(Account(1, 5.0f), Account(2, -1.0f), Account(3, 10f), Account(4, 12f)) 

println(s"result ${doFilter(accounts, 1, 0f)}") 

私は、フィルタステートメントを分割し、中間結果を確認するが、私は、私はそれをより多くのScalaの方法を行うことができます願っていたことができます..私はのようなものを考えました。

しかし、これは機能しません。目的の動作を実装する機能(または流暢)な方法はありますか?

答えて

2

次のコードは、からわずかな修正でありますthis SO answer from Rex Kerr

implicit class KestrelPattern[A](private val repr: A) extends AnyVal { 
    def tee[B](f: A => B) = { f(repr); repr } // B is thrown away (Unit) 
} 

彼はそれをtapと呼びました。私はを選んだのは、unix teeコマンドと似ているからです。

使用方法:作品を一致

scala> List[Int](3,5,7).tee{x => if (x.isEmpty) println("ERROR")}.sum 
res42: Int = 15 

scala> List[Int]().tee{x => if (x.isEmpty) println("ERROR")}.sum 
ERROR 
res43: Int = 0 
2

これを一度必要とする場合は、中間結果を記録するのが最も簡単な方法です。あなたはいくつかの場所でこれを必要とする場合は、ビット拡張メソッドを使用してよりよいコードを作ることができます。

implicit class ListOps[+A](val list: List[A]) extends AnyVal { 
    def logIfEmpty(): List[A] = { 
     if (list.isEmpty) { 
     println("Error: empty list") 
     // or whatever; you can even pass it as an argument 
    } 
    list 
    } 
} 

その後、あなたはこのようにそれを使用することができます:

def doFilter(list: List[Account], focusId: Int, thresHold: Float): List[Account] = list 
    .filter(_.id == focusId) 
    .logIfEmpty() 
    .filter(_.balance >= thresHold) 
1

パターン、あなたのコードのエラーが2番目のケースで_を返すようにしようとしているという事実から来て、あなたはなぜこのためherehereをチェックすることもできます問題となる可能性があります。

accounts.filter(_.id == 1) match { 
     case List() => { println("error"); List() } 
     case x => x.filter(_.balance > 1.0) 
} 
// res19: List[Account] = List(Account(1,5.0)) 


accounts.filter(_.id == 5) match { 
     case List() => { println("error"); List() } 
     case x => x.filter(_.balance > 1.0) 
} 
// error 
// res20: List[Account] = List() 
関連する問題