green-creeper
green-creeper

Reputation: 316

Scala Map fold instead of find

Trying to replace find in Map with fold with no success. I made simple example to not dive into details of my types. How to replace it with fold?

val s: Map[String, Int] = Map("1" -> 1, "2" -> 0, "3" -> 1)

s.find(_._2 == 0) match {
  case Some((_, 0)) => "F"
  case _ => "T"
}

Upvotes: 0

Views: 75

Answers (1)

sgvd
sgvd

Reputation: 3939

Although there indeed may be better solutions than a fold for your problem, this is the answer to your question:

val s: Map[String, Int] = Map("1" -> 1, "2" -> 0, "3" -> 1)

s.foldLeft("T") {
  case (_, (_, 0)) => "F"
  case (res, _) => res
}

The point is that you have to keep passing on the result gathered so far in the default case.

Upvotes: 2

Related Questions