Skip to content

Instantly share code, notes, and snippets.

@non
Created November 13, 2012 05:47
Show Gist options
  • Save non/4064198 to your computer and use it in GitHub Desktop.
Save non/4064198 to your computer and use it in GitHub Desktop.
Add map + flatMap to Function1-3 with no overhead
object RichF {
implicit class RichF1[A, Z](val f: A => Z) extends AnyVal {
def map[Y](g: Z => Y): A => Y =
(a: A) => g(f(a))
def flatMap[Y](g: Z => A => Y): A => Y =
(a: A) => g(f(a))(a)
}
implicit class RichF2[A, B, Z](val f: (A, B) => Z) extends AnyVal {
def map[Y](g: Z => Y): (A, B) => Y =
(a: A, b: B) => g(f(a, b))
def flatMap[Y](g: Z => (A, B) => Y): (A, B) => Y =
(a: A, b: B) => g(f(a, b))(a, b)
}
implicit class RichF3[A, B, C, Z](val f: (A, B, C) => Z) extends AnyVal {
def map[Y](g: Z => Y): (A, B, C) => Y =
(a: A, b: B, c: C) => g(f(a, b, c))
def flatMap[Y](g: Z => (A, B, C) => Y): (A, B, C) => Y =
(a: A, b: B, c: C) => g(f(a, b, c))(a, b, c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment