Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code repetition in Scala
// The following three functions have code repetition.
// How might this repetition be factored out?
//
// What about the same examples in other programming environments?
object CodeRepetition {
import missing._
def sequenceOption[A](x: List[Option[A]]): Option[List[A]] =
x.foldRight(Some(Nil): Option[List[A]])((a, b) =>
for {
x <- a
y <- b
} yield x::y)
def sequenceList[A](x: List[List[A]]): List[List[A]] =
x.foldRight(List(Nil): List[List[A]])((a, b) =>
for {
x <- a
y <- b
} yield x::y)
def sequenceReader[A, T](x: List[Function1[T, A]]): Function1[T, List[A]] =
x.foldRight((_ => Nil): Function1[T, List[A]])((a, b) =>
for {
x <- a
y <- b
} yield x::y)
}
// Missing parts of the standard library.
object missing {
implicit class Function1Missing[T, A](f: T => A) {
// Add a `map` method to `Function1` to be used in a for-comprehension.
// The `map` method is the same as `andThen`. You can notice this in the
// type-signature of `andThen`, which follows the form of `map`.
def map[B](g: A => B): T => B =
f andThen g
// Add a `flatMap` method to `Function1` to be used in a for-comprehension.
// Like the `map` method for `Function1`, there is only one possible
// implementation with the type of `flatMap`.
//
// Note that the type follows the structure of `flatMap` as in some other examples:
// (List [A])(A => List [B]) => List [B]
// (Option [A])(A => Option [B]) => Option [B]
// (Function1[T, A])(A => Function1[T, B]) => Function1[T, B]
def flatMap[B](g: A => T => B): T => B =
t => g(f(t))(t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment