Skip to content

Instantly share code, notes, and snippets.

@SebastianAas
SebastianAas / sum_of_collections.scala
Last active January 21, 2021 13:05
Sum of collections
for {
a1 <- Future(Set(1, 2, 3))
b1 <- Future(Set(1, 2, 3))
} yield {
for {
x <- a1
y <- b1 if y > 2
} yield {
x + y
}
@SebastianAas
SebastianAas / example.scala
Created January 21, 2021 10:21
Example - For Comprehension
def example() = {
val a1 = Set(1, 2, 3)
val b2 = Set(1, 2, 3)
for {
x <- a1
y <- b2 if y > 2
} yield {
x + y
}
}
@SebastianAas
SebastianAas / example_desugar.scala
Created January 21, 2021 10:22
Example Desugar
def example() = {
val a1 = Set(1, 2, 3)
val b2 = Set(1, 2, 3)
a1
.flatMap(x =>
b2
.withFilter(y => y > 2)
.map(y => x + y)
)
}
@SebastianAas
SebastianAas / SetF.scala
Last active January 21, 2021 10:32
SetF
final case class SetF[A](_future: Future[Iterable[A]]) extends AnyVal {
def future: Future[Set[A]] = _future.map(_.toSet)
def flatMap[B](f: A => SetF[B]): SetF[B] = {
val newFuture: Future[Set[B]] = for {
list: Set[A] <- future
result: Set[Set[B]] <- Future.sequence(list.map(f(_).future))
} yield {
result.flatten
}
SetF(newFuture)
@SebastianAas
SebastianAas / ExampleImproved.scala
Last active January 21, 2021 13:30
Example Improved
def addAllCombinations() = {
val a = Future(Set(1, 2, 3))
val b = Future(Set(1, 2, 3))
for {
x <- SetF(a)
y <- SetF(b) if y > 2
} yield {
x + y
}
} // Result: Future[Set(4,5,6)]
@SebastianAas
SebastianAas / SetF.scala
Created January 21, 2021 10:27
Companion class SetF
object SetF {
def lift[A](f: Future[A]): SetF[A] = SetF(f.map(Set(_)))
def apply[A](o: Iterable[A]): SetF[A] =
SetF(Future.successful(o match {
case o: Set[_] => o.asInstanceOf[Set[A]]
case o => o.toSet
}))
}
@SebastianAas
SebastianAas / Example2.scala
Last active January 21, 2021 12:33
Example 2
def example2() = {
val a = Future(0.5)
val b = Future(Set(1, 2, 3))
for {
x <- SetF.lift(a)
y <- SetF(b)
} yield {
x * y
}
}