SlideShare a Scribd company logo
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) 
}

More Related Content

What's hot

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
Philip 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 2020
Luka Jacobowitz
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
Philip 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 traverse
Luka Jacobowitz
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
Luka Jacobowitz
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
Philip Schwarz
 
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 All
John De Goes
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
Eric Torreborre
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
samthemonad
 
Running Free with the Monads
Running Free with the MonadsRunning Free with the Monads
Running Free with the Monads
kenbot
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
John 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 Tagless
John De Goes
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
Piotr Paradziński
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
Oliver Daff
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John 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
 

What's hot (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...
 

Viewers also liked

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: Notes
Roberto 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
 
ScalaMatsuri 2014 LT
ScalaMatsuri 2014 LTScalaMatsuri 2014 LT
ScalaMatsuri 2014 LT
Daisuke Kasuya
 
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 Scala
Jacek 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 scala
Stratio
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 

Viewers also liked (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
 

Similar to 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 Monads
Lawrence 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 Programming
Namuk Park
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
Hermann 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 pattern
Markus Klink
 
Thesis
ThesisThesis
Thesis
Drew Ferkin
 
Thesis PPT
Thesis PPTThesis PPT
Thesis PPT
Drew Ferkin
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
Philip Schwarz
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang 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 & Analytics
John 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 meetup
Mikhail Girkin
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
Philip Schwarz
 
하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4하스켈 프로그래밍 입문 4
하스켈 프로그래밍 입문 4
Kwang Yul Seo
 
Algebraic Data Types and Origami Patterns
Algebraic Data Types and Origami PatternsAlgebraic Data Types and Origami Patterns
Algebraic Data Types and Origami Patterns
Vasil Remeniuk
 
Hardcore functional programming
Hardcore functional programmingHardcore functional programming
Hardcore functional programming
Leonardo Andres Garcia Crespo
 
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
Debasish Ghosh
 

Similar to 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
ThesisThesis
Thesis
 
Thesis PPT
Thesis PPTThesis PPT
Thesis PPT
 
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
 

Recently uploaded

Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
AnkitaPandya11
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 

Recently uploaded (20)

Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 

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) }