Skip to content

Instantly share code, notes, and snippets.

@Sam-Serpoosh
Last active November 10, 2015 05:20
Show Gist options
  • Save Sam-Serpoosh/a1b38a139bde737a61fe to your computer and use it in GitHub Desktop.
Save Sam-Serpoosh/a1b38a139bde737a61fe to your computer and use it in GitHub Desktop.
A pattern of converting a one-track-input Function to a two-track-input Function for better function-composition-ability in the presence of Option types. Inspired by Maybe Monad.
// Convert a One-Track-Input Function to Two-Track-Input Function for better
// Composability of Function in the presence of Option types
def bindOption[A, B](f: A => Option[B]): Option[A] => Option[B] = {
(input) => input match {
case Some(a) => f(a)
case None => None
}
}
def otherBindOption[A, B](f: A => B, default: B): Option[A] => B = {
(input) => input match {
case Some(a) => f(a)
case None => default
}
}
def stringToOptionInt(s: String): Option[Int] = Some(s.toInt)
def stringToInt(s: String): Int = s.toInt
// Testing Them
val twoTrackFunction = bindOption(stringToOptionInt)
val otherTwoTrackFunction = otherBindOption(stringToInt, 10)
val str = Some("123")
val str2: Option[String] = None
val result = twoTrackFunction(str)
val result2 = otherTwoTrackFunction(None)
println(result) // #=> Some(123)
println(result2) // #=> 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment