Skip to content

Instantly share code, notes, and snippets.

@bmarcot
Last active December 16, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmarcot/5508717 to your computer and use it in GitHub Desktop.
Save bmarcot/5508717 to your computer and use it in GitHub Desktop.
For-comprehension
def f(xs: List[Int]): List[List[(Int, Int)]] = {
xs match {
case Nil => List(List())
case x :: xs => for {
ns <- f(xs)
i <- 0 to x
} yield (x, i) :: ns
}
}
f(List(1, 2, 3))
// f(List(1, 2))
// res0: List[List[(Int, Int)]] = List(List((1,0), (2,0)), List((1,1), (2,0)), List((1,0), (2,1)), List((1,1), (2,1)), List((1,0), (2,2)), List((1,1), (2,2)))
List(('a', 1), ('d', 1), ('l', 1), ('r', 1)).toMap
def substract(xs: List[(Char, Int)], ys: List[(Char, Int)]): List[(Char, Int)] = {
def substractAux(xs: List[(Char, Int)], ys: List[(Char, Int)]): List[(Char, Int)] = {
for {
(char, occ) <- xs
} yield ys.toMap.get(char) match {
case Some(o) => (char, occ - o)
case _ => (char, occ)
}
}
substractAux(xs, ys).filter(_._2 > 0)
}
substract(List(('a', 1), ('d', 1), ('l', 1), ('r', 1)), List(('r', 1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment