SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
FP in Scala 
Walk with monsters (ADTs)
Applicative Functor 
// id function: 
// def id[A](a: A): A = a 
// compose function: 
// def compose[A,B,C](f: B => C, g: 
A => B): A => C = 
// a => f(g(a)) 
trait Functor[F[_]] { 
def map[A,B](fa: F[A])(f: A => 
B): F[B] 
} 
// Functor Law 
// identity: map(x)(id) == x 
// composition: map(a)(compose(f, 
g)) == map(map(a,g), f) 
trait Applictive[F[_]] extends Functor 
[F] { 
def unit[A](a: => A): F[A] 
def ap[A,B](la: F[A])(f: F[A => B]): F 
[B] 
override def map[A, B](la: F[A])(f: A 
=> B): F[B] = 
ap(la)(unit(f)) 
} 
// Applicative Law 
// identity: ap(a, unit(id)) == a 
// composition: ap(ap(a, g), f) == ap(a, ap 
(g, ap(f, unit(compose)))) 
// homomorphism: ap(unit(a), unit(f)) == 
unit(f(a)) 
// interchange: ap(unit(a), f) == ap(f, unit(f 
=> f(x))) 
trait Monad[F[_]] extends Applictive[F] { 
def unit[A](a: => A): F[A] 
def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] 
override def ap[A,B](la: F[A])(f: F[A => B]): F 
[B] = 
flatMap(f)(t1 => flatMap(la)(t2 => unit(t1 
(t2)))) 
override def map[A,B](ma: F[A])(f: A => B): F 
[B] = 
flatMap(ma)(a => unit(f(a))) 
} 
// Monad Law 
// left identity: f(a) == flatmap(unit(a), f) 
// right identity: a == flatMap(a, x => unit(x)) 
// associativity: flatMap(a, x => flatMap(f(x), g)) == 
flatMap(flatMap(a, f), g)
Applicative Functor 
Functor 
Take one function 
with one input and 
apply onto the 
value inside 
content 
Monad 
Take function(s) 
that can apply to 
values inside 
contents, and also 
can change 
behavior in the 
process of apply 
function(s) 
Applicative Functor 
Take one function 
with multiple input 
and apply onto the 
values inside 
contents
Applicative Functor 
Functor 
def oneVarFunc: Int => Int = 
{ 
_ + 1 
} 
val x1 = Some(1) 
x1.map(oneVarFunc) 
get Some(2) 
Monad 
val x1 = Some(1) 
val x2 = Some(2) 
val x3 = Some(3) 
x1.flatMap { r1 => { 
r1 match { 
case 1 => x2.flatMap { 
r2 => Some(r1 * r2) 
} 
case _ => x3.flatMap { 
r3 => Some(r1 + r3) 
} 
} 
} 
get Some(2) 
Applicative Functor 
def twoVarFunc: (Int, Int) => Int = {_ + _} 
val x1 = Some(1) 
val x2 = Some(2) 
val x3 = None 
x2.ap(x1.map(twoVarFunc.curried)) 
get Some(3) 
x3.ap(x2.map(twoVarFunc.curried)) 
get None 
def zip[U](that: Future[U]): Future[(T, U)]
Why Applicative Functor 
1. Because it is less restrictive, it in fact easier to reason. 
2. It is also a key part of Traversable ADT 
3. Not all Applicative functor is Monad 
a. Indefinite length Stream 
b. Multidimensional Array 
4. Different Applicative functor can compose, different 
Monad can not compose (has to use Monad 
Transformer) 
a. def compose[A,B,C](f: A => M[B], g: B => M[C]): A => 
M[C] = ???
Monad Transformer 
Want a Applicative/Monad that has multiple 
property by compose 2 or more 
Applicatives/Monads, for example. 
List[Option[Future[Int]]] 
Can this type be also a Applicative/Monad, has ap 
and flatMap defined. Can we just have generic way 
to do this instead of write one for every type?
Applicative Composition 
trait Functor[F[_]] { 
def map[A,B](fa: F[A])(f: A => B): F[B] 
} 
trait Applictive[F[_]] extends Functor[F] { 
def unit[A](a: => A): F[A] 
def ap[A,B](la: F[A])(f: F[A => B]): F[B] 
override def map[A, B](la: F[A])(f: A => B): F[B] = 
ap(la)(unit(f)) 
def apply2[A, B, C](fa: => F[A], fb: => F[B])(f: (A, B) => C): F 
[C] = 
ap(fb)(map(fa)(f.curried)) 
} 
trait CompositionApplicative[F[_], G[_]] extends Applicative 
[({type λ[α] = F[G[α]]})#λ] { 
implicit def F: Applicative[F] 
implicit def G: Applicative[G] 
def ap[A, B](fa: => F[G[A]])(f: => F[G[A => B]]): F[G[B]] 
= 
F.apply2(f, fa)((ff, ga) => G.ap(ga)(ff)) 
def unit[A](a: => A): F[G[A]] = F.unit(G.unit(a)) 
} 
Yes, we can do it for Applicative in a generic way
Monad Composition 
trait Monad[F[_]] extends Applictive[F] { 
def unit[A](a: => A): F[A] 
def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] 
override def ap[A,B](la: F[A])(f: F[A => B]): F[B] = 
flatMap(f)(t1 => flatMap(la)(t2 => unit(t1(t2)))) 
override def map[A,B](ma: F[A])(f: A => B): F[B] = 
flatMap(ma)(a => unit(f(a))) 
} 
case class OptionT[M[_],A](value: M[Option[A]]) { 
self => 
def unit(a: A)(implicit m: Monad[M]): OptionT[M, A] = 
new OptionT[M, A](m.unit(Some(a))) 
def flatMap[B](f: A => OptionT[M, B])(implicit m: Monad[M]) 
: OptionT[M, B] = new OptionT[M, B]( 
m.flatMap(self.value) { 
case None => m.unit(None) 
case Some(a) => f(a).value 
}) 
} 
No, we can not do it for Monad in a generic way
Foldable 
trait Semigroup[A] { 
def op(a: A, b: A): A 
} 
trait Monoid[A] extends Semigroup[A] { 
val zero: A 
} 
trait Foldable[F[_]] { 
def foldMap[A,B](fa: F[A], f: A => B)(implicit m: Monoid 
[B]): B 
/* 
def fold[M: Monoid](t: F[M]): M // also called reduce with 
variance 
def foldRight[A, B](t: F[A], z: => B, f: (A, B) => B): B 
def foldLeft[A, B](t: F[A], z: B, f: (B, A) => B): B 
def foldr1[A, B](t: F[A], f: (A, => A) => A): Option[A] 
def foldl1[A, B](t: F[A], f: (A, A) => A): Option[A] 
*/ 
} 
This the definition of 
Monoid and Foldable, 
simple and generic but very 
very useful. 
In fact, it is the conceptual 
base for MapReduce 
With Applicative and 
Foldable, we will introduce 
Traversable
Foldable 
val IntMonoid = new Monoid[Int] { 
def op(a: Int, b: Int): Int = a * b 
val zero: Int = 1 
} 
val ListFodable = new Foldable[List] { 
def foldMap[A, B](t: List[A], f: A => B)(implicit m: Monoid[B]): B = 
t.foldRight(m.zero)((a,b) => m.op(f(a), b)) 
} 
object test { 
val x1 = List(1,2,3,4) 
val r1 = ListFodable.foldMap(x1, (x: Int) => x)(IntMonoid) 
} 
Foldable use a Monoid to 
go through a structure, and 
in the process return some 
aggregated value with the 
original structure collapsed.
Traversable 
Traversable is a generalized Foldable 
Foldable use a Monoid to go through a structure, and in the 
process return some aggregated value with the original 
structure collapsed. 
Traversable use a Applicative go through a structure, and 
in the process return some aggregated value with the 
original structure kept.
Traversable 
trait Foldable[F[_]] { 
def foldMap[A, M: Monoid](t: F[A], f: A => M): M 
} 
trait Applicative[F[_]] extends Functor[F]{ 
def unit[A](a: => A): F[A] 
def ap[A,B](fa: F[A])(fab: F[A => B]): F[B] 
override def map[A,B](t: F[A])(f: A => B): F[B] = 
ap(t)(unit(f)) 
} 
type Const[A, B] = A 
implicit def monoidApplicative[M](m: Monoid[M]) = 
new Applicative[({ type f[x] = Const[M, x] })#f] { 
def unit[A](a: => A): M = m.zero 
override def ap[A,B](m1: M)(m2: M): M = m.op 
(m1, m2) 
} 
import scala.Predef.identity 
trait Traversable[T[_]] extends Functor[T] with Foldable[T] { 
def traverse[F[_]: Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]] // = 
sequence(map(t)(f)) 
def sequence[F[_]: Applicative, A](tfa: T[F[A]]): F[T[A]] = traverse(identity 
[F[A]], tfa) 
// def mapM[M[_]: Monad, A, B](f: A => M[B], t: T[A]): M[T[B]] = ??? 
// def sequenceM[M[_]: Monad](tmb: T[M[B]]): M[T[B]] = ??? 
type Id[A] = A 
val Identity = new Applicative[Id] { 
def unit[A](a: => A) = a 
def ap[A,B](a: A)(f: A => B): B = f(a) 
} 
override def map[A, B](k: T[A])(f: A => B) = traverse[Id, A, B](f, k) 
(Identity) 
override def foldMap[A, M](as: T[A], f: A => M)(implicit m: Monoid[M]): 
M= 
traverse[({type f[x] = Const[M,x]})#f,A,Nothing](f, as)(monoidApplicative 
(m))
Traversable 
As you can see, transverse preserves the structure, it is the 
strength and weakness. 
The sequence method is very interesting, F[G[A]], if F is a 
Traversable, and G is a Applicative, it in fact can be 
reversed as G[F[A]] 
It also works with Monad as every Monad is a Applicative 
(does not means Monad composable, as you need a 
Traversable) 
Traversable is composable, like Applicative
Traversable in Action 
import scala.language.higherKinds 
val OptionApplicatable = new Applicative[Option] { 
def unit[A](a: => A) = Some(a) 
def ap[A,B](a: Option[A])(f: Option[A => B]): Option[B] = 
f.flatMap { 
t1 => a.flatMap { 
t2 => unit(t1(t2)) 
} 
} 
} 
val ListTraversable = new Traversable[List] { 
def traverse[F[_], A, B](f: A => F[B], t: List[A])(implicit m: 
Applicative[F]): F[List[B]] = 
t.foldRight(m.unit(List[B]()))((a, fbs) => m.zip(f(a),fbs)(_ 
:: _)) 
} 
object test { 
val x1 = List(1,2,3,4) 
val x2 = List(Option(1), Option(2), Option(3)) 
val x3 = List(Option(1), Option(2), Option(3), Option(null)) 
def f1(a: Int): Option[Int] = Some(a) 
val r1 = ListTraversable.traverse(f1, x1)(OptionApplicatable) 
val r2 = ListTraversable.sequence(x2)(OptionApplicatable) 
val r3 = ListTraversable.sequence(x3)(OptionApplicatable) 
}

Contenu connexe

Tendances

Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
 
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Philip Schwarz
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsKirill Kozlov
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Philip Schwarz
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)stasimus
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a categorysamthemonad
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monadskenbot
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New GameJohn De Goes
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final TaglessJohn De Goes
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scalaPiotr Paradziński
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type ClassesJohn De Goes
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Piotr Paradziński
 

Tendances (20)

Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
Symmetry in the interrelation of flatMap/foldMap/traverse and flatten/fold/se...
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 

En vedette

Functional Programming in Scala #4-1
Functional Programming in Scala #4-1Functional Programming in Scala #4-1
Functional Programming in Scala #4-1Yoshihiro Shimizu
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#Riccardo Terrell
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: NotesRoberto Casadei
 
Functional Programming in Scala Reading #2
Functional Programming in Scala Reading #2Functional Programming in Scala Reading #2
Functional Programming in Scala Reading #2Naoyuki Yamada
 
関数プログラミングことはじめ
関数プログラミングことはじめ関数プログラミングことはじめ
関数プログラミングことはじめNaoki Kitora
 
20150207 何故scalaを選んだのか
20150207 何故scalaを選んだのか20150207 何故scalaを選んだのか
20150207 何故scalaを選んだのかKatsunori Kanda
 
Introduction to Functional Programming in Scala
Introduction to Functional Programming in ScalaIntroduction to Functional Programming in Scala
Introduction to Functional Programming in ScalaJacek Laskowski
 
JavaからScalaへの継続的なマイグレーション
JavaからScalaへの継続的なマイグレーションJavaからScalaへの継続的なマイグレーション
JavaからScalaへの継続的なマイグレーションMakoto Fukuhara
 
浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ
浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ
浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみNaoyuki Yamada
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaStratio
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

En vedette (12)

Functional Programming in Scala #4-1
Functional Programming in Scala #4-1Functional Programming in Scala #4-1
Functional Programming in Scala #4-1
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
Functional Programming in Scala Reading #2
Functional Programming in Scala Reading #2Functional Programming in Scala Reading #2
Functional Programming in Scala Reading #2
 
関数プログラミングことはじめ
関数プログラミングことはじめ関数プログラミングことはじめ
関数プログラミングことはじめ
 
ScalaMatsuri 2014 LT
ScalaMatsuri 2014 LTScalaMatsuri 2014 LT
ScalaMatsuri 2014 LT
 
20150207 何故scalaを選んだのか
20150207 何故scalaを選んだのか20150207 何故scalaを選んだのか
20150207 何故scalaを選んだのか
 
Introduction to Functional Programming in Scala
Introduction to Functional Programming in ScalaIntroduction to Functional Programming in Scala
Introduction to Functional Programming in Scala
 
JavaからScalaへの継続的なマイグレーション
JavaからScalaへの継続的なマイグレーションJavaからScalaへの継続的なマイグレーション
JavaからScalaへの継続的なマイグレーション
 
浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ
浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ
浪江町タブレットで採用した、 Cordovaで作るHTML5のAndroidアプリのしくみ
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similaire à Fp in scala with adts

The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)Eric Torreborre
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to MonadsLawrence Evans
 
Monad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingMonad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingNamuk Park
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersHermann Hueck
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Philip Schwarz
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator patternMarkus Klink
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and EffectsRaymond Roestenburg
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Ruslan Shevchenko
 
Monads - Dublin Scala meetup
Monads - Dublin Scala meetupMonads - Dublin Scala meetup
Monads - Dublin Scala meetupMikhail Girkin
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1Philip Schwarz
 
하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4Kwang Yul Seo
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsVasil Remeniuk
 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
 

Similaire à Fp in scala with adts (20)

The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)The Essence of the Iterator Pattern (pdf)
The Essence of the Iterator Pattern (pdf)
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
 
Monad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingMonad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional Programming
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
 
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
Kleisli composition, flatMap, join, map, unit - implementation and interrelat...
 
Essence of the iterator pattern
Essence of the iterator patternEssence of the iterator pattern
Essence of the iterator pattern
 
Thesis PPT
Thesis PPTThesis PPT
Thesis PPT
 
Thesis
ThesisThesis
Thesis
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
 
Monads - Dublin Scala meetup
Monads - Dublin Scala meetupMonads - Dublin Scala meetup
Monads - Dublin Scala meetup
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
 
Hardcore functional programming
Hardcore functional programmingHardcore functional programming
Hardcore functional programming
 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain Models
 

Dernier

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Dernier (20)

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Fp in scala with adts

  • 1. FP in Scala Walk with monsters (ADTs)
  • 2. Applicative Functor // id function: // def id[A](a: A): A = a // compose function: // def compose[A,B,C](f: B => C, g: A => B): A => C = // a => f(g(a)) trait Functor[F[_]] { def map[A,B](fa: F[A])(f: A => B): F[B] } // Functor Law // identity: map(x)(id) == x // composition: map(a)(compose(f, g)) == map(map(a,g), f) trait Applictive[F[_]] extends Functor [F] { def unit[A](a: => A): F[A] def ap[A,B](la: F[A])(f: F[A => B]): F [B] override def map[A, B](la: F[A])(f: A => B): F[B] = ap(la)(unit(f)) } // Applicative Law // identity: ap(a, unit(id)) == a // composition: ap(ap(a, g), f) == ap(a, ap (g, ap(f, unit(compose)))) // homomorphism: ap(unit(a), unit(f)) == unit(f(a)) // interchange: ap(unit(a), f) == ap(f, unit(f => f(x))) trait Monad[F[_]] extends Applictive[F] { def unit[A](a: => A): F[A] def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] override def ap[A,B](la: F[A])(f: F[A => B]): F [B] = flatMap(f)(t1 => flatMap(la)(t2 => unit(t1 (t2)))) override def map[A,B](ma: F[A])(f: A => B): F [B] = flatMap(ma)(a => unit(f(a))) } // Monad Law // left identity: f(a) == flatmap(unit(a), f) // right identity: a == flatMap(a, x => unit(x)) // associativity: flatMap(a, x => flatMap(f(x), g)) == flatMap(flatMap(a, f), g)
  • 3. Applicative Functor Functor Take one function with one input and apply onto the value inside content Monad Take function(s) that can apply to values inside contents, and also can change behavior in the process of apply function(s) Applicative Functor Take one function with multiple input and apply onto the values inside contents
  • 4. Applicative Functor Functor def oneVarFunc: Int => Int = { _ + 1 } val x1 = Some(1) x1.map(oneVarFunc) get Some(2) Monad val x1 = Some(1) val x2 = Some(2) val x3 = Some(3) x1.flatMap { r1 => { r1 match { case 1 => x2.flatMap { r2 => Some(r1 * r2) } case _ => x3.flatMap { r3 => Some(r1 + r3) } } } get Some(2) Applicative Functor def twoVarFunc: (Int, Int) => Int = {_ + _} val x1 = Some(1) val x2 = Some(2) val x3 = None x2.ap(x1.map(twoVarFunc.curried)) get Some(3) x3.ap(x2.map(twoVarFunc.curried)) get None def zip[U](that: Future[U]): Future[(T, U)]
  • 5. Why Applicative Functor 1. Because it is less restrictive, it in fact easier to reason. 2. It is also a key part of Traversable ADT 3. Not all Applicative functor is Monad a. Indefinite length Stream b. Multidimensional Array 4. Different Applicative functor can compose, different Monad can not compose (has to use Monad Transformer) a. def compose[A,B,C](f: A => M[B], g: B => M[C]): A => M[C] = ???
  • 6. Monad Transformer Want a Applicative/Monad that has multiple property by compose 2 or more Applicatives/Monads, for example. List[Option[Future[Int]]] Can this type be also a Applicative/Monad, has ap and flatMap defined. Can we just have generic way to do this instead of write one for every type?
  • 7. Applicative Composition trait Functor[F[_]] { def map[A,B](fa: F[A])(f: A => B): F[B] } trait Applictive[F[_]] extends Functor[F] { def unit[A](a: => A): F[A] def ap[A,B](la: F[A])(f: F[A => B]): F[B] override def map[A, B](la: F[A])(f: A => B): F[B] = ap(la)(unit(f)) def apply2[A, B, C](fa: => F[A], fb: => F[B])(f: (A, B) => C): F [C] = ap(fb)(map(fa)(f.curried)) } trait CompositionApplicative[F[_], G[_]] extends Applicative [({type λ[α] = F[G[α]]})#λ] { implicit def F: Applicative[F] implicit def G: Applicative[G] def ap[A, B](fa: => F[G[A]])(f: => F[G[A => B]]): F[G[B]] = F.apply2(f, fa)((ff, ga) => G.ap(ga)(ff)) def unit[A](a: => A): F[G[A]] = F.unit(G.unit(a)) } Yes, we can do it for Applicative in a generic way
  • 8. Monad Composition trait Monad[F[_]] extends Applictive[F] { def unit[A](a: => A): F[A] def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] override def ap[A,B](la: F[A])(f: F[A => B]): F[B] = flatMap(f)(t1 => flatMap(la)(t2 => unit(t1(t2)))) override def map[A,B](ma: F[A])(f: A => B): F[B] = flatMap(ma)(a => unit(f(a))) } case class OptionT[M[_],A](value: M[Option[A]]) { self => def unit(a: A)(implicit m: Monad[M]): OptionT[M, A] = new OptionT[M, A](m.unit(Some(a))) def flatMap[B](f: A => OptionT[M, B])(implicit m: Monad[M]) : OptionT[M, B] = new OptionT[M, B]( m.flatMap(self.value) { case None => m.unit(None) case Some(a) => f(a).value }) } No, we can not do it for Monad in a generic way
  • 9. Foldable trait Semigroup[A] { def op(a: A, b: A): A } trait Monoid[A] extends Semigroup[A] { val zero: A } trait Foldable[F[_]] { def foldMap[A,B](fa: F[A], f: A => B)(implicit m: Monoid [B]): B /* def fold[M: Monoid](t: F[M]): M // also called reduce with variance def foldRight[A, B](t: F[A], z: => B, f: (A, B) => B): B def foldLeft[A, B](t: F[A], z: B, f: (B, A) => B): B def foldr1[A, B](t: F[A], f: (A, => A) => A): Option[A] def foldl1[A, B](t: F[A], f: (A, A) => A): Option[A] */ } This the definition of Monoid and Foldable, simple and generic but very very useful. In fact, it is the conceptual base for MapReduce With Applicative and Foldable, we will introduce Traversable
  • 10. Foldable val IntMonoid = new Monoid[Int] { def op(a: Int, b: Int): Int = a * b val zero: Int = 1 } val ListFodable = new Foldable[List] { def foldMap[A, B](t: List[A], f: A => B)(implicit m: Monoid[B]): B = t.foldRight(m.zero)((a,b) => m.op(f(a), b)) } object test { val x1 = List(1,2,3,4) val r1 = ListFodable.foldMap(x1, (x: Int) => x)(IntMonoid) } Foldable use a Monoid to go through a structure, and in the process return some aggregated value with the original structure collapsed.
  • 11. Traversable Traversable is a generalized Foldable Foldable use a Monoid to go through a structure, and in the process return some aggregated value with the original structure collapsed. Traversable use a Applicative go through a structure, and in the process return some aggregated value with the original structure kept.
  • 12. Traversable trait Foldable[F[_]] { def foldMap[A, M: Monoid](t: F[A], f: A => M): M } trait Applicative[F[_]] extends Functor[F]{ def unit[A](a: => A): F[A] def ap[A,B](fa: F[A])(fab: F[A => B]): F[B] override def map[A,B](t: F[A])(f: A => B): F[B] = ap(t)(unit(f)) } type Const[A, B] = A implicit def monoidApplicative[M](m: Monoid[M]) = new Applicative[({ type f[x] = Const[M, x] })#f] { def unit[A](a: => A): M = m.zero override def ap[A,B](m1: M)(m2: M): M = m.op (m1, m2) } import scala.Predef.identity trait Traversable[T[_]] extends Functor[T] with Foldable[T] { def traverse[F[_]: Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]] // = sequence(map(t)(f)) def sequence[F[_]: Applicative, A](tfa: T[F[A]]): F[T[A]] = traverse(identity [F[A]], tfa) // def mapM[M[_]: Monad, A, B](f: A => M[B], t: T[A]): M[T[B]] = ??? // def sequenceM[M[_]: Monad](tmb: T[M[B]]): M[T[B]] = ??? type Id[A] = A val Identity = new Applicative[Id] { def unit[A](a: => A) = a def ap[A,B](a: A)(f: A => B): B = f(a) } override def map[A, B](k: T[A])(f: A => B) = traverse[Id, A, B](f, k) (Identity) override def foldMap[A, M](as: T[A], f: A => M)(implicit m: Monoid[M]): M= traverse[({type f[x] = Const[M,x]})#f,A,Nothing](f, as)(monoidApplicative (m))
  • 13. Traversable As you can see, transverse preserves the structure, it is the strength and weakness. The sequence method is very interesting, F[G[A]], if F is a Traversable, and G is a Applicative, it in fact can be reversed as G[F[A]] It also works with Monad as every Monad is a Applicative (does not means Monad composable, as you need a Traversable) Traversable is composable, like Applicative
  • 14. Traversable in Action import scala.language.higherKinds val OptionApplicatable = new Applicative[Option] { def unit[A](a: => A) = Some(a) def ap[A,B](a: Option[A])(f: Option[A => B]): Option[B] = f.flatMap { t1 => a.flatMap { t2 => unit(t1(t2)) } } } val ListTraversable = new Traversable[List] { def traverse[F[_], A, B](f: A => F[B], t: List[A])(implicit m: Applicative[F]): F[List[B]] = t.foldRight(m.unit(List[B]()))((a, fbs) => m.zip(f(a),fbs)(_ :: _)) } object test { val x1 = List(1,2,3,4) val x2 = List(Option(1), Option(2), Option(3)) val x3 = List(Option(1), Option(2), Option(3), Option(null)) def f1(a: Int): Option[Int] = Some(a) val r1 = ListTraversable.traverse(f1, x1)(OptionApplicatable) val r2 = ListTraversable.sequence(x2)(OptionApplicatable) val r3 = ListTraversable.sequence(x3)(OptionApplicatable) }