Skip to content

Instantly share code, notes, and snippets.

@bpk-t
Created June 19, 2015 14:46
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 bpk-t/f9c60a1099cae7956d72 to your computer and use it in GitHub Desktop.
Save bpk-t/f9c60a1099cae7956d72 to your computer and use it in GitHub Desktop.
FP in Scala 4 - 4.3, 4.4, 4.4
/**
* Created by BPK_t on 2015/06/19.
*/
object Main {
def main(args: Array[String]) {
val a = Some(100)
val b = Some(200.0)
val c = map2(a,b)((x,y)=>x+y)
println(c)
val x = sequence(List(Some(1),Some(2),Some(3)))
println(x)
val x2 = sequence(List(Some(1),None,Some(3)))
println(x2)
val y = traverse(List("1", "2", "3"))(x => Some(x.toInt))
println(y)
}
//4.3
def map2[A,B,C](a:Option[A], b:Option[B])(f:(A,B)=>C) : Option[C] = {
a.flatMap(x => b.map(y => f(x,y)))
}
//4.4
def sequence[A](a:List[Option[A]]):Option[List[A]] = a match {
case Nil => Some(Nil)
case _ => map2(a.head, sequence(a.tail))(_ :: _)
}
//4.5
def traverse[A, B](a: List[A])(f: A => Option[B]): Option[List[B]] = {
a match {
case Nil => Some(Nil)
case _ => map2(f(a.head), traverse(a.tail)(f))(_ :: _)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment