SlideShare a Scribd company logo
1 of 39
Download to read offline
ORIGAMI
patterns with
Algebraic Data Types
           @remeniuk
What is “algebra”?
1. A set of elements
2.Some operations that map
   elements to elements
List
1. Elements: “list” and “list
   element”
2.Operations: Nil and ::(cons)
In programming languages,
algebraic data types are defined
with the set of constructors that
wrap other types
Haskell offers a very expressive syntax for
     defining Algebraic Data Types.



Here's how Boolean can be implemented:

data Boolean = True | False
True and False are data type constructors



  data Boolean = True | False

This is a closed data type - once you've declared the
constructors, you no longer can add more
dynamically
In Scala, algebraic data type
         declaration
   is a bit more verbose...
sealed trait Boolean
case object True extends Boolean
case object False extends Boolean

     *sealed closes the data type!
Scala                  vs   Haskell
Simple extensibility via
inheritence - open data    >    Syntactic clarity

types
Regular algebraic data types
• Unit type
• Sum type: data Boolean = True | False
• Singleton type : data X a = X a
     Combination of sum and singleton :
     Either a b = Left a | Right b
• Product type: data List a = Nil|a :: List a
  (combination of unit, sum and product)
• Recursive type
List of Integers in Haskell:

data ListI = NilI | ConsI Integer ListI
data ListI = NilI | ConsI Integer ListI


                  Usage:
let list = ConsI 3 (ConsI 2 (ConsI 1 NilI))
Not much more complex in Scala...


trait ListI
case object NilI extends ListI
case class ConsI(head: Int, tail: ListI)
extends ListI
...especially, with some convenience methods...


trait ListI {
    def ::(value: Int) = ConsI(value, this)
}

case object NilI extends ListI
case class ConsI(value: Int, list: ListI)
extends ListI
...and here we are:

val list = 3 :: 2 :: 1 :: NilI
Lets make our data types
   more useful
...making them parametrically polymorphic


               BEFORE:
trait ListI {
    def ::(value: Int) = ConsI(value, this)
}

case object NilI extends ListI
case class ConsI(value: Int, list: ListI)
extends ListI
...making them parametrically polymorphic


                   AFTER:

sealed trait ListG[+A] {
    def ::[B >: A](value: B) = ConsG[B](value, this)
}
case object NilG extends ListG[Nothing]
case class ConsG[A](head: A, tail: ListG[A]) extends
ListG[A]
Defining a simple, product algebraic
type for binary tree is a no-brainer:


sealed trait BTreeG[+A]

case class Tip[A](value: A) extends
BTreeG[A]
case class Bin[A](left: BTreeG[A], right:
BTreeG[A]) extends BTreeG[A]
ListG and BTreeG are Generalized
Algebraic Data Types

 And the programming approach
     itself is called Generic
         Programming
Let's say, we want to find a sum of all
the elements in the ListG and
BTreeG, now...
Let's say, we want to find a sum of all
the elements in the ListG and
BTreeG, now...


               fold
def foldL[B](n: B)(f: (B, A) => B)
    (list: ListG[A]): B = list match {
        case NilG => n
        case ConsG(head, tail) =>
            f(foldL(n)(f)(tail), head)
    }
}




foldL[Int, Int](0)(_ + _)(list)
def foldT[B](f: A => B)(g: (B, B) => B)
(tree: BTreeG[A]): B =
   tree match {
     case Tip(value) => f(value)
     case Bin(left, right) =>
       g(foldT(f)(g)(tree),foldT(f)(g)(tree))

}




foldT[Int, Int](0)(x => x)(_ + _)(tree)
Obviously, foldL and foldT have
very much in common.
Obviously, foldL and foldT have
very much in common.

In fact, the biggest difference is in
the shape of the data
That would be great, if we could
abstract away from data type...
That would be great, if we could
abstract away from data type...

   With Datatype Generic
    programming we can!
Requirements:

• Fix data type (recursive data type)
• Datatype-specific instance of
  Bifunctor
1. Fix type

         Fix [F [_, _], A]


Higher-kinded shape      Type parameter of
(pair, list, tree,...)   the shape
Let's create an instance of Fix for
List shape

trait ListF[+A, +B]

case object NilF extends ListF[Nothing, Nothing]

case class ConsF[A, B](head: A, tail: B) extends
ListF[A, B]


         type List[A] = Fix[ListF, A]
2. Datatype-specific instance
   of Bifunctor

trait Bifunctor[F[_, _]] {
    def bimap[A, B, C, D](k: F[A, B],
          f: A => C, g: B => D): F[C, D]
}


         Defines mapping for the shape
Bifunctor instance for ListF

implicit val listFBifunctor = new Bifunctor[ListF]{

    def bimap[A, B, C, D](k: ListF[A,B], f: A => C,
                      g: B => D): ListF[C,D] =

    k match {
      case NilF => NilF
      case ConsF(head, tail) => ConsF(f(head), g(tail))
    }

}
It turns out, that a wide number of
other generic operations on data types
can be expressed via bimap!
def map[A, B, F [_, _]](f : A => B)(t : Fix [F, A])
(implicit ft : Bifunctor [F]) : Fix [F, B]

    def fold[A, B, F [_, _]](f : F[A, B] => B)(t : Fix[F,A])
(implicit ft : Bifunctor [F]) : B

    def unfold [A, B, F [_, _]] (f : B => F[A, B]) (b : B)
(implicit ft : Bifunctor [F]) : Fix[F, A]

    def hylo [A, B, C, F [_, _]] (f : B => F[A, B]) (g : F[A, C]
=> C)(b: B) (implicit ft : Bifunctor [F]) : C

    def build [A, F [_, _]] (f : {def apply[B]: (F [A, B] => B)
=> B}): Fix[F, A]




                 See http://goo.gl/I4OBx
This approach is called
                  Origami patterns

• Origami patterns can be applied to generic
  data types!
• Include the following GoF patterns
   o Composite (algebraic data type itself)
   o Iterator (map)
   o Visitor (fold / hylo)
   o Builder (build / unfold)
Those operations are called
      30 loc      Origami patterns

• The patterns can be applied to generic data
  types!
             vs 250 loc in pure Java
• Include the following GoF patterns
   o Composite (algebraic data type itself)
   o Iterator (map)
   o Visitor (fold)
   o Builder (build / unfold / hylo)
Live demo!
 http://goo.gl/ysv5Y
Thanks for watching!

More Related Content

What's hot (19)

Monoids
MonoidsMonoids
Monoids
 
One dimensional arrays
One dimensional arraysOne dimensional arrays
One dimensional arrays
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
 
Array ppt
Array pptArray ppt
Array ppt
 
Arrays
ArraysArrays
Arrays
 
Lecture1 classes4
Lecture1 classes4Lecture1 classes4
Lecture1 classes4
 
Functor Laws
Functor LawsFunctor Laws
Functor Laws
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascience
 
Arrays
ArraysArrays
Arrays
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Array
ArrayArray
Array
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Thesis PPT
Thesis PPTThesis PPT
Thesis PPT
 
Python - variable types
Python - variable typesPython - variable types
Python - variable types
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Strings and pointers
Strings and pointersStrings and pointers
Strings and pointers
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 

Viewers also liked

[Не]практичные типы
[Не]практичные типы[Не]практичные типы
[Не]практичные типыVasil Remeniuk
 
Photoshop Tutorial Booklet
Photoshop Tutorial BookletPhotoshop Tutorial Booklet
Photoshop Tutorial BookletGraveney School
 
How to Intensify Images in Photoshop
How to Intensify Images in PhotoshopHow to Intensify Images in Photoshop
How to Intensify Images in PhotoshopMetrodesk
 
Building a semantic-based decision support system to optimize the energy use ...
Building a semantic-based decision support system to optimize the energy use ...Building a semantic-based decision support system to optimize the energy use ...
Building a semantic-based decision support system to optimize the energy use ...Gonçal Costa Jutglar
 
MODAClouds Decision Support System for Cloud Service Selection
MODAClouds Decision Support System for Cloud Service SelectionMODAClouds Decision Support System for Cloud Service Selection
MODAClouds Decision Support System for Cloud Service SelectionLDBC council
 
Tutorial on photoshop
Tutorial on photoshopTutorial on photoshop
Tutorial on photoshopDiamondLSilva
 
Ocean Globe, Ocean Geospatial Appliance
Ocean Globe, Ocean Geospatial ApplianceOcean Globe, Ocean Geospatial Appliance
Ocean Globe, Ocean Geospatial ApplianceHigh Tech Maui
 
Happiness short film and Website tv briefs
Happiness short film and Website  tv briefsHappiness short film and Website  tv briefs
Happiness short film and Website tv briefsGraveney School
 
Russian Revolution Part 1
Russian Revolution Part 1Russian Revolution Part 1
Russian Revolution Part 1Joseph Fuertsch
 
Russian Revolution Part 3
Russian Revolution Part 3Russian Revolution Part 3
Russian Revolution Part 3Joseph Fuertsch
 
Russian Revolution Part 2
Russian Revolution Part 2Russian Revolution Part 2
Russian Revolution Part 2Joseph Fuertsch
 
Linked Data for the Enterprise: Opportunities and Challenges
Linked Data for the Enterprise: Opportunities and ChallengesLinked Data for the Enterprise: Opportunities and Challenges
Linked Data for the Enterprise: Opportunities and ChallengesMarin Dimitrov
 
Vietnam...how did we get there
Vietnam...how did we get thereVietnam...how did we get there
Vietnam...how did we get thereJoseph Fuertsch
 
Internet-enabled GIS for Planners
Internet-enabled GIS for PlannersInternet-enabled GIS for Planners
Internet-enabled GIS for PlannersJohn Reiser
 

Viewers also liked (20)

[Не]практичные типы
[Не]практичные типы[Не]практичные типы
[Не]практичные типы
 
The Great War
The Great WarThe Great War
The Great War
 
Photoshop Tutorial Booklet
Photoshop Tutorial BookletPhotoshop Tutorial Booklet
Photoshop Tutorial Booklet
 
Great depression 2010
Great depression 2010Great depression 2010
Great depression 2010
 
How to Intensify Images in Photoshop
How to Intensify Images in PhotoshopHow to Intensify Images in Photoshop
How to Intensify Images in Photoshop
 
Nioxon to ford 2011
Nioxon to ford 2011Nioxon to ford 2011
Nioxon to ford 2011
 
Building a semantic-based decision support system to optimize the energy use ...
Building a semantic-based decision support system to optimize the energy use ...Building a semantic-based decision support system to optimize the energy use ...
Building a semantic-based decision support system to optimize the energy use ...
 
MODAClouds Decision Support System for Cloud Service Selection
MODAClouds Decision Support System for Cloud Service SelectionMODAClouds Decision Support System for Cloud Service Selection
MODAClouds Decision Support System for Cloud Service Selection
 
Tutorial on photoshop
Tutorial on photoshopTutorial on photoshop
Tutorial on photoshop
 
Ocean Globe, Ocean Geospatial Appliance
Ocean Globe, Ocean Geospatial ApplianceOcean Globe, Ocean Geospatial Appliance
Ocean Globe, Ocean Geospatial Appliance
 
Happiness short film and Website tv briefs
Happiness short film and Website  tv briefsHappiness short film and Website  tv briefs
Happiness short film and Website tv briefs
 
Russian Revolution Part 1
Russian Revolution Part 1Russian Revolution Part 1
Russian Revolution Part 1
 
Russian Revolution Part 3
Russian Revolution Part 3Russian Revolution Part 3
Russian Revolution Part 3
 
Mapping the Way
Mapping the WayMapping the Way
Mapping the Way
 
Afghanistan
AfghanistanAfghanistan
Afghanistan
 
Fist 2008
Fist 2008Fist 2008
Fist 2008
 
Russian Revolution Part 2
Russian Revolution Part 2Russian Revolution Part 2
Russian Revolution Part 2
 
Linked Data for the Enterprise: Opportunities and Challenges
Linked Data for the Enterprise: Opportunities and ChallengesLinked Data for the Enterprise: Opportunities and Challenges
Linked Data for the Enterprise: Opportunities and Challenges
 
Vietnam...how did we get there
Vietnam...how did we get thereVietnam...how did we get there
Vietnam...how did we get there
 
Internet-enabled GIS for Planners
Internet-enabled GIS for PlannersInternet-enabled GIS for Planners
Internet-enabled GIS for Planners
 

Similar to Algebraic Data Types and Origami Patterns

Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellMichel Rijnders
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Philip Schwarz
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaDaniel Sebban
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalazoxbow_lakes
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryMeetu Maltiar
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsKirill Kozlov
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric 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
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 

Similar to Algebraic Data Types and Origami Patterns (20)

Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
Monad Fact #4
Monad Fact #4Monad Fact #4
Monad Fact #4
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
 
Zippers
ZippersZippers
Zippers
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Monoids
MonoidsMonoids
Monoids
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Thesis
ThesisThesis
Thesis
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
(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
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 

More from Vasil Remeniuk

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикVasil Remeniuk
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Vasil Remeniuk
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Vasil Remeniuk
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Vasil Remeniuk
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform researchVasil Remeniuk
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform ResearchVasil Remeniuk
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaVasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovVasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovVasil Remeniuk
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, PauliusVasil Remeniuk
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Vasil Remeniuk
 
Spark intro by Adform Research
Spark intro by Adform ResearchSpark intro by Adform Research
Spark intro by Adform ResearchVasil Remeniuk
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaVasil Remeniuk
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Vasil Remeniuk
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Vasil Remeniuk
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + ElkVasil Remeniuk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхVasil Remeniuk
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTVasil Remeniuk
 

More from Vasil Remeniuk (20)

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и Программатик
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform research
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform Research
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, Paulius
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)
 
Spark intro by Adform Research
Spark intro by Adform ResearchSpark intro by Adform Research
Spark intro by Adform Research
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius Valatka
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + Elk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событиях
 
ETL со Spark
ETL со SparkETL со Spark
ETL со Spark
 
Funtional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWTFuntional Reactive Programming with Examples in Scala + GWT
Funtional Reactive Programming with Examples in Scala + GWT
 

Recently uploaded

AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 

Recently uploaded (20)

AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 

Algebraic Data Types and Origami Patterns

  • 2. What is “algebra”? 1. A set of elements 2.Some operations that map elements to elements
  • 3. List 1. Elements: “list” and “list element” 2.Operations: Nil and ::(cons)
  • 4. In programming languages, algebraic data types are defined with the set of constructors that wrap other types
  • 5. Haskell offers a very expressive syntax for defining Algebraic Data Types. Here's how Boolean can be implemented: data Boolean = True | False
  • 6. True and False are data type constructors data Boolean = True | False This is a closed data type - once you've declared the constructors, you no longer can add more dynamically
  • 7. In Scala, algebraic data type declaration is a bit more verbose...
  • 8. sealed trait Boolean case object True extends Boolean case object False extends Boolean *sealed closes the data type!
  • 9. Scala vs Haskell Simple extensibility via inheritence - open data > Syntactic clarity types
  • 10. Regular algebraic data types • Unit type • Sum type: data Boolean = True | False • Singleton type : data X a = X a Combination of sum and singleton : Either a b = Left a | Right b • Product type: data List a = Nil|a :: List a (combination of unit, sum and product) • Recursive type
  • 11. List of Integers in Haskell: data ListI = NilI | ConsI Integer ListI
  • 12. data ListI = NilI | ConsI Integer ListI Usage: let list = ConsI 3 (ConsI 2 (ConsI 1 NilI))
  • 13. Not much more complex in Scala... trait ListI case object NilI extends ListI case class ConsI(head: Int, tail: ListI) extends ListI
  • 14. ...especially, with some convenience methods... trait ListI { def ::(value: Int) = ConsI(value, this) } case object NilI extends ListI case class ConsI(value: Int, list: ListI) extends ListI
  • 15. ...and here we are: val list = 3 :: 2 :: 1 :: NilI
  • 16. Lets make our data types more useful
  • 17. ...making them parametrically polymorphic BEFORE: trait ListI { def ::(value: Int) = ConsI(value, this) } case object NilI extends ListI case class ConsI(value: Int, list: ListI) extends ListI
  • 18. ...making them parametrically polymorphic AFTER: sealed trait ListG[+A] { def ::[B >: A](value: B) = ConsG[B](value, this) } case object NilG extends ListG[Nothing] case class ConsG[A](head: A, tail: ListG[A]) extends ListG[A]
  • 19. Defining a simple, product algebraic type for binary tree is a no-brainer: sealed trait BTreeG[+A] case class Tip[A](value: A) extends BTreeG[A] case class Bin[A](left: BTreeG[A], right: BTreeG[A]) extends BTreeG[A]
  • 20. ListG and BTreeG are Generalized Algebraic Data Types And the programming approach itself is called Generic Programming
  • 21. Let's say, we want to find a sum of all the elements in the ListG and BTreeG, now...
  • 22. Let's say, we want to find a sum of all the elements in the ListG and BTreeG, now... fold
  • 23. def foldL[B](n: B)(f: (B, A) => B) (list: ListG[A]): B = list match { case NilG => n case ConsG(head, tail) => f(foldL(n)(f)(tail), head) } } foldL[Int, Int](0)(_ + _)(list)
  • 24. def foldT[B](f: A => B)(g: (B, B) => B) (tree: BTreeG[A]): B = tree match { case Tip(value) => f(value) case Bin(left, right) => g(foldT(f)(g)(tree),foldT(f)(g)(tree)) } foldT[Int, Int](0)(x => x)(_ + _)(tree)
  • 25. Obviously, foldL and foldT have very much in common.
  • 26. Obviously, foldL and foldT have very much in common. In fact, the biggest difference is in the shape of the data
  • 27. That would be great, if we could abstract away from data type...
  • 28. That would be great, if we could abstract away from data type... With Datatype Generic programming we can!
  • 29. Requirements: • Fix data type (recursive data type) • Datatype-specific instance of Bifunctor
  • 30. 1. Fix type Fix [F [_, _], A] Higher-kinded shape Type parameter of (pair, list, tree,...) the shape
  • 31. Let's create an instance of Fix for List shape trait ListF[+A, +B] case object NilF extends ListF[Nothing, Nothing] case class ConsF[A, B](head: A, tail: B) extends ListF[A, B] type List[A] = Fix[ListF, A]
  • 32. 2. Datatype-specific instance of Bifunctor trait Bifunctor[F[_, _]] { def bimap[A, B, C, D](k: F[A, B], f: A => C, g: B => D): F[C, D] } Defines mapping for the shape
  • 33. Bifunctor instance for ListF implicit val listFBifunctor = new Bifunctor[ListF]{ def bimap[A, B, C, D](k: ListF[A,B], f: A => C, g: B => D): ListF[C,D] = k match { case NilF => NilF case ConsF(head, tail) => ConsF(f(head), g(tail)) } }
  • 34. It turns out, that a wide number of other generic operations on data types can be expressed via bimap!
  • 35. def map[A, B, F [_, _]](f : A => B)(t : Fix [F, A]) (implicit ft : Bifunctor [F]) : Fix [F, B] def fold[A, B, F [_, _]](f : F[A, B] => B)(t : Fix[F,A]) (implicit ft : Bifunctor [F]) : B def unfold [A, B, F [_, _]] (f : B => F[A, B]) (b : B) (implicit ft : Bifunctor [F]) : Fix[F, A] def hylo [A, B, C, F [_, _]] (f : B => F[A, B]) (g : F[A, C] => C)(b: B) (implicit ft : Bifunctor [F]) : C def build [A, F [_, _]] (f : {def apply[B]: (F [A, B] => B) => B}): Fix[F, A] See http://goo.gl/I4OBx
  • 36. This approach is called Origami patterns • Origami patterns can be applied to generic data types! • Include the following GoF patterns o Composite (algebraic data type itself) o Iterator (map) o Visitor (fold / hylo) o Builder (build / unfold)
  • 37. Those operations are called 30 loc Origami patterns • The patterns can be applied to generic data types! vs 250 loc in pure Java • Include the following GoF patterns o Composite (algebraic data type itself) o Iterator (map) o Visitor (fold) o Builder (build / unfold / hylo)