SlideShare a Scribd company logo
1 of 4
Download to read offline
Healthy Code
January - 2015
14
Code Jugalbandi
Article
Ryan
Dhaval
Healthy Code
January - 2015
15
Jugalbandi inspires and fuels our desire to learn by focusing
on dialogue and exploration. More languages in the room
meant more perspectives too. Exploring a paradigm through
any single language could. Above all, Code Jugalbandi is a
Creator and Listener
We met regularly over a period of several months, exploring
some key issues related to Functional Programming
(FP). This culminated in a live Code Jugalbandi at the
Functional Conference in Bengaluru, 2014. During the
FP Code Jugalbandi, we explored nine themes, which
became melodies. Similar to the musical Jugalbandi, there
are two roles: creator and listener. We called the creator of
the melody Bramha and the one who listens and responds
Krishna
explore one such melody: The Expression Problem.
The Expression Problem
The Expression Problem was coined by Philip Wadler.
Wikipedia states that the goal of the Expression Problem
is to
cases to the datatype and new functions over the datatype,
without recompiling existing code, and while retaining
static type safety (e.g. no casts). According to Wadler,
“Whether a language can solve the Expression Problem is a
salient indicator of its capacity for expression.”
The Expression Problem - Clojure
BRAMHA: In OOP, we model our domain concepts by
creating our own types i.e., using classes and interfaces. In
a geometric shape, say the Circle, in Clojure.
(defrecord Circle [radius])
(Circle. 11)
(:radius (Circle. 11))
BRAMHA: Classes in OO act as containers for structured
data, as well as behaviour acting on the structured data. In
Clojure, records just take care of the structure.
BRAMHA: In Clojure, the corollary of an Interface is
a Protocol:
(defprotocol Shape
(area [shape])
(perimeter [shape]))
BRAMHA: We can extend our Circle type to implement
the Shape protocol, e.g.
(extend-type Circle
Shape
(area [circle]
(* (:r circle) (:r circle) Math/PI)))
BRAMHA: At this stage we have a simple type-based
dispatch for our protocol method area. Clojure is more
powerful but less performant polymorphic dispatch
through multimethods.
(area (Circle. 10))
(area (Rect. 10 20))
BRAMHA
something like this: (EP1) create a new type that implements
an existing interface
BRAMHA
our existing Shape protocol:
(defrecord Rect [length width]
Shape
(area [rect]
(* (:length rect) (:width rect))))
KRISHNA
allow you to create new classes to implement existing
BRAMHA: Yes, agreed, but the second part of the Expression
Problem is harder to solve in some OO languages:
(EP2) implement a new interface for an existing type
Moreover (EP1) and (EP2) should be possible without having
in working with third party code that you cannot recompile.
To achieve (EP2) with Clojure we can do this:
(defprotocol Graphic
(draw [this]))
(extend-type Circle
Graphic
(draw [this] (puts “O”)))
KRISHNA: Clojure fares well with both (EP1) and (EP2). Let
me show you how Scala addresses the Expression Problem.
The Expression Problem - Scala
KRISHNA: We start by creating the Circle and Rectangle as
data classes.
Healthy Code
January - 2015
16
case class Circle(r: Int)
case class Rectangle(l: Int, w: Int)
KRISHNA Shape
that I can perform on Circle and Rectangle.
trait Shape[T] {
def area(t: T): Double
def perimeter(t: T): Double
}
Then I implement the trait for Circle, say,
implicit object CircleOps extends Shape[Circle] {
def area(c: Circle): Double = Math.PI * c.r * c.r
def perimeter(c: Circle): Double = 2 * Math.PI
* c.r }
KRISHNA
def area[T](t: T)(implicit s: Shape[T]): Double =
s.area(t)
def perimeter[T](t: T)(implicit s: Shape[T]):
Double =
s.perimeter(t)
KRISHNA: Returning to the Expression Problem, we can
solve (EP2) like this in Scala:
trait Graphics[T] {
def draw(t: T): Unit
}
implicit object CircleGraphics extends
Graphics[Circle] {
def draw(c: Circle) = println(“O”)
}
def draw[T](t: T)(implicit g: Graphics[T]) =
g.draw(t)
KRISHNA
a new Right Triangle type and implement the existing
interfaces.
case class RTriangle(b: Int, h: Int)
import Math._
implicit object RTriangleOps extends Shape[RTriangle]
with Graphics[RTriangle] {
def area(rt: RTriangle) = 0.5 * rt.b * rt.h
def perimeter(rt: RTriangle) =
rt.b + rt.h + (sqrt(pow(rt.b, 2) +
pow(rt.h, 2))
def draw(rt: RTriangle) = println(rt)
}
BRAHMA: Scala solves both (EP1) and (EP2), albeit with
some syntactic noise around the use of implicit objects.
Let me show you how concise Haskell is at solving the
Expression Problem.
The Expression Problem - Haskell
BRAMHA
with a few sub-types:
data Shape = Circle {radius :: Float}
| Rect {length :: Float, width ::Float}
deriving Show
BRAMHA: To create an area method that is polymorphic
over the Shape sub-types:
area :: Shape -> Float
area (Circle r) = 3.14 * r^2
area (Rect l w) = l * w
BRAMHA
In (EP1) adding a new sub-type to the Shape algebraic type
would require adding a clause for the new subtype to each
function I declared over the type (implying a recompile),
In (EP2) adding a new function acting on existing algebraic
types is trivial.
The Expression Problem with TypeClasses
Instead of unifying the concepts Circle and Rect as the Shape
abstract data type, we could use Haskell typeclasses to unify
to not name clash with the above code).
data Circle_ = Circle_ {radius_ :: Float}
data Rect_ = Rect_ {length_ :: Float, width_ ::
Float}
class Shape_ a where
area_ :: a -> Float
perimeter_ :: a -> Float
Healthy Code
January - 2015
17
BRAMHA: Adding a new data type that implements an
existing typeclass is easy (EP1):
instance Shape_ Circle_ where
area_ (Circle_ r) = pi * r^2
perimeter_(Circle_ r) = 2 * pi * r
Extending an existing type with a new interface is simple
too (EP2):
class Graphics_ a where
draw_ :: a -> IO ()
instance Graphics_ Circle_ where
draw_ (Circle_ r) = putStrLn (show r)
KRISHNA: In OOP classes, we can combine type with
a clear separation between type and behaviour.
BRAMHA
is that objects contain mutable state. In FP languages, we use
immutable values in place of mutable state. For example,
the Circle and Rect in all three languages were some form of
KRISHNA: The Expression Problem also asks that you can
extend types with interfaces without needing to recompile
the code you are extending. Our three languages are quite
BRAMHA: Scala is more strictly typed, but also fares well
by allowing extension of code without recompiling it. If we
look, both the Scala and Clojure both resemble Haskell in the
KRISHNA: Yes, and Haskell deals with types in a
sophisticated yet simple way, but it is less dynamic and more
limited in solving this aspect of the (EP).
BRAMHA
KRISHNA
than traditional OO does, but then again, many OO
languages have evolved and are much more dynamic these
days. In fact, using Java Generics, the Expression Problem
can be solved, except that it would be syntactically very noisy
Ryan is a software developer,
coach and advisor, based in Cape
Town. He has been working with
code for more than 15 years. Ryan
assists individuals and teams
to manage the evolution and
complexity of their software
systems. Ryan is a passionate
learner and enjoys facilitating
learning in others.
Dhavalahands-ondeveloperand
mentor, believes that software
then a craft. For him writing
software brings his creativity
to the fore. His interests are in
architecting applications ground
up, estabilishing environments,
transitioning and orienting
teams to Agile way of working
by embedding himself within
teams.
CodeJugalbandi
object
BRAHMA: True, and besides, there are very few purely FP
or OO languages. Still, we can say that FP does have good
answers to the (EP).
References
Learn more from

More Related Content

What's hot

Expected Questions TC
Expected Questions TCExpected Questions TC
Expected Questions TCSANTOSH RATH
 
Expected questions tc
Expected questions tcExpected questions tc
Expected questions tcSANTOSH RATH
 
Cs6503 theory of computation april may 2017
Cs6503 theory of computation april may 2017Cs6503 theory of computation april may 2017
Cs6503 theory of computation april may 2017appasami
 
Looking for Invariant Operators in Argumentation
Looking for Invariant Operators in ArgumentationLooking for Invariant Operators in Argumentation
Looking for Invariant Operators in ArgumentationCarlo Taticchi
 
Logics and Ontologies for Portuguese Understanding
Logics and Ontologies for Portuguese UnderstandingLogics and Ontologies for Portuguese Understanding
Logics and Ontologies for Portuguese UnderstandingValeria de Paiva
 
NFA Non Deterministic Finite Automata by Mudasir khushik
NFA Non Deterministic Finite Automata by Mudasir khushikNFA Non Deterministic Finite Automata by Mudasir khushik
NFA Non Deterministic Finite Automata by Mudasir khushikMudsaraliKhushik
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysisDattatray Gandhmal
 
Clojure - an introduction (and some CFML)
Clojure - an introduction (and some CFML)Clojure - an introduction (and some CFML)
Clojure - an introduction (and some CFML)Kai Koenig
 
A Concurrent Language for Argumentation
A Concurrent Language for ArgumentationA Concurrent Language for Argumentation
A Concurrent Language for ArgumentationCarlo Taticchi
 
Theory of Computation Lecture Notes
Theory of Computation Lecture NotesTheory of Computation Lecture Notes
Theory of Computation Lecture NotesFellowBuddy.com
 
Introduction to the theory of computation
Introduction to the theory of computationIntroduction to the theory of computation
Introduction to the theory of computationprasadmvreddy
 
A Concurrent Language for Argumentation: Preliminary Notes
A Concurrent Language for Argumentation: Preliminary NotesA Concurrent Language for Argumentation: Preliminary Notes
A Concurrent Language for Argumentation: Preliminary NotesCarlo Taticchi
 

What's hot (18)

Expected Questions TC
Expected Questions TCExpected Questions TC
Expected Questions TC
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Expected questions tc
Expected questions tcExpected questions tc
Expected questions tc
 
Cs6503 theory of computation april may 2017
Cs6503 theory of computation april may 2017Cs6503 theory of computation april may 2017
Cs6503 theory of computation april may 2017
 
Pascal programming language
Pascal programming languagePascal programming language
Pascal programming language
 
Looking for Invariant Operators in Argumentation
Looking for Invariant Operators in ArgumentationLooking for Invariant Operators in Argumentation
Looking for Invariant Operators in Argumentation
 
Logics and Ontologies for Portuguese Understanding
Logics and Ontologies for Portuguese UnderstandingLogics and Ontologies for Portuguese Understanding
Logics and Ontologies for Portuguese Understanding
 
Cfg part i
Cfg   part iCfg   part i
Cfg part i
 
NFA Non Deterministic Finite Automata by Mudasir khushik
NFA Non Deterministic Finite Automata by Mudasir khushikNFA Non Deterministic Finite Automata by Mudasir khushik
NFA Non Deterministic Finite Automata by Mudasir khushik
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysis
 
Clojure - an introduction (and some CFML)
Clojure - an introduction (and some CFML)Clojure - an introduction (and some CFML)
Clojure - an introduction (and some CFML)
 
A Concurrent Language for Argumentation
A Concurrent Language for ArgumentationA Concurrent Language for Argumentation
A Concurrent Language for Argumentation
 
Theory of Computation Lecture Notes
Theory of Computation Lecture NotesTheory of Computation Lecture Notes
Theory of Computation Lecture Notes
 
Model toc
Model tocModel toc
Model toc
 
Introduction to the theory of computation
Introduction to the theory of computationIntroduction to the theory of computation
Introduction to the theory of computation
 
Dfa basics
Dfa basicsDfa basics
Dfa basics
 
A Concurrent Language for Argumentation: Preliminary Notes
A Concurrent Language for Argumentation: Preliminary NotesA Concurrent Language for Argumentation: Preliminary Notes
A Concurrent Language for Argumentation: Preliminary Notes
 
Automata Theory
Automata TheoryAutomata Theory
Automata Theory
 

Viewers also liked

Multimedia Final
Multimedia FinalMultimedia Final
Multimedia Finalboirablava
 
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015Dhaval Dalal
 
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr20154-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015Dhaval Dalal
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentDhaval Dalal
 

Viewers also liked (6)

Water
WaterWater
Water
 
Matrimonio
MatrimonioMatrimonio
Matrimonio
 
Multimedia Final
Multimedia FinalMultimedia Final
Multimedia Final
 
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
 
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr20154-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

Similar to CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue

LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийSigma Software
 
Evaluation and analysis of ALGOL, PASCAL and ADA
Evaluation and analysis of ALGOL, PASCAL and ADAEvaluation and analysis of ALGOL, PASCAL and ADA
Evaluation and analysis of ALGOL, PASCAL and ADADilanka Dias
 
CS 354 Programmable Shading
CS 354 Programmable ShadingCS 354 Programmable Shading
CS 354 Programmable ShadingMark Kilgard
 
The Ring programming language version 1.5.4 book - Part 178 of 185
The Ring programming language version 1.5.4 book - Part 178 of 185The Ring programming language version 1.5.4 book - Part 178 of 185
The Ring programming language version 1.5.4 book - Part 178 of 185Mahmoud Samir Fayed
 
Programing paradigm & implementation
Programing paradigm & implementationPrograming paradigm & implementation
Programing paradigm & implementationBilal Maqbool ツ
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp languageDavid Gu
 
The Ring programming language version 1.5.2 book - Part 174 of 181
The Ring programming language version 1.5.2 book - Part 174 of 181The Ring programming language version 1.5.2 book - Part 174 of 181
The Ring programming language version 1.5.2 book - Part 174 of 181Mahmoud Samir Fayed
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++oggyrao
 
The Ring programming language version 1.8 book - Part 93 of 202
The Ring programming language version 1.8 book - Part 93 of 202The Ring programming language version 1.8 book - Part 93 of 202
The Ring programming language version 1.8 book - Part 93 of 202Mahmoud Samir Fayed
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingLex Sheehan
 

Similar to CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue (20)

3.5
3.53.5
3.5
 
Special topics in finance lecture 2
Special topics in finance   lecture 2Special topics in finance   lecture 2
Special topics in finance lecture 2
 
PARADIGM IT.pptx
PARADIGM IT.pptxPARADIGM IT.pptx
PARADIGM IT.pptx
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола Мозговий
 
Scope
ScopeScope
Scope
 
Evaluation and analysis of ALGOL, PASCAL and ADA
Evaluation and analysis of ALGOL, PASCAL and ADAEvaluation and analysis of ALGOL, PASCAL and ADA
Evaluation and analysis of ALGOL, PASCAL and ADA
 
CS 354 Programmable Shading
CS 354 Programmable ShadingCS 354 Programmable Shading
CS 354 Programmable Shading
 
Introduction to F#
Introduction to F#Introduction to F#
Introduction to F#
 
The Ring programming language version 1.5.4 book - Part 178 of 185
The Ring programming language version 1.5.4 book - Part 178 of 185The Ring programming language version 1.5.4 book - Part 178 of 185
The Ring programming language version 1.5.4 book - Part 178 of 185
 
F# for Scala developers
F# for Scala developersF# for Scala developers
F# for Scala developers
 
ALGOL ailesi programlama dilleri
ALGOL ailesi programlama dilleriALGOL ailesi programlama dilleri
ALGOL ailesi programlama dilleri
 
lec9_ref.pdf
lec9_ref.pdflec9_ref.pdf
lec9_ref.pdf
 
Programing paradigm & implementation
Programing paradigm & implementationPrograming paradigm & implementation
Programing paradigm & implementation
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
 
The Ring programming language version 1.5.2 book - Part 174 of 181
The Ring programming language version 1.5.2 book - Part 174 of 181The Ring programming language version 1.5.2 book - Part 174 of 181
The Ring programming language version 1.5.2 book - Part 174 of 181
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Report on c and c++
Report on c and c++Report on c and c++
Report on c and c++
 
The Ring programming language version 1.8 book - Part 93 of 202
The Ring programming language version 1.8 book - Part 93 of 202The Ring programming language version 1.8 book - Part 93 of 202
The Ring programming language version 1.8 book - Part 93 of 202
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional ProgrammingGo Beyond Higher Order Functions: A Journey into Functional Programming
Go Beyond Higher Order Functions: A Journey into Functional Programming
 

More from Dhaval Dalal

Test Pyramid in Microservices Context
Test Pyramid in Microservices ContextTest Pyramid in Microservices Context
Test Pyramid in Microservices ContextDhaval Dalal
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharpDhaval Dalal
 
Json Viewer Stories
Json Viewer StoriesJson Viewer Stories
Json Viewer StoriesDhaval Dalal
 
Mars rover-extension
Mars rover-extensionMars rover-extension
Mars rover-extensionDhaval Dalal
 
How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?Dhaval Dalal
 
Approaching ATDD/BDD
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDDDhaval Dalal
 
Paradigms Code jugalbandi
Paradigms Code jugalbandiParadigms Code jugalbandi
Paradigms Code jugalbandiDhaval Dalal
 
Data Reconciliation
Data ReconciliationData Reconciliation
Data ReconciliationDhaval Dalal
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar20153-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015Dhaval Dalal
 
The tao-of-transformation-workshop
The tao-of-transformation-workshopThe tao-of-transformation-workshop
The tao-of-transformation-workshopDhaval Dalal
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with GroovyDhaval Dalal
 
Language portfolio
Language portfolioLanguage portfolio
Language portfolioDhaval Dalal
 

More from Dhaval Dalal (20)

Test Pyramid in Microservices Context
Test Pyramid in Microservices ContextTest Pyramid in Microservices Context
Test Pyramid in Microservices Context
 
Code Retreat
Code RetreatCode Retreat
Code Retreat
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
 
Json Viewer Stories
Json Viewer StoriesJson Viewer Stories
Json Viewer Stories
 
Value Objects
Value ObjectsValue Objects
Value Objects
 
Mars rover-extension
Mars rover-extensionMars rover-extension
Mars rover-extension
 
How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?
 
Approaching ATDD/BDD
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDD
 
Paradigms Code jugalbandi
Paradigms Code jugalbandiParadigms Code jugalbandi
Paradigms Code jugalbandi
 
Data Reconciliation
Data ReconciliationData Reconciliation
Data Reconciliation
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
CodeRetreat
CodeRetreatCodeRetreat
CodeRetreat
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar20153-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
 
The tao-of-transformation-workshop
The tao-of-transformation-workshopThe tao-of-transformation-workshop
The tao-of-transformation-workshop
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
 
Language portfolio
Language portfolioLanguage portfolio
Language portfolio
 
Code jugalbandi
Code jugalbandiCode jugalbandi
Code jugalbandi
 

Recently uploaded

Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Software Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey HightowerSoftware Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey HightowerAnchore
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
QMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfQMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfROWELL MARQUINA
 
full stack practical assignment msc cs.pdf
full stack practical assignment msc cs.pdffull stack practical assignment msc cs.pdf
full stack practical assignment msc cs.pdfHulkTheDevil
 
Transport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MITransport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MIRomil Mishra
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationDianaGray10
 
Tetracrom printing process for packaging with CMYK+
Tetracrom printing process for packaging with CMYK+Tetracrom printing process for packaging with CMYK+
Tetracrom printing process for packaging with CMYK+Antonio de Llamas
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdfHCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdfROWELL MARQUINA
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Automation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions managementAutomation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions managementDianaGray10
 

Recently uploaded (20)

Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Software Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey HightowerSoftware Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey Hightower
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
QMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdfQMMS Lesson 2 - Using MS Excel Formula.pdf
QMMS Lesson 2 - Using MS Excel Formula.pdf
 
full stack practical assignment msc cs.pdf
full stack practical assignment msc cs.pdffull stack practical assignment msc cs.pdf
full stack practical assignment msc cs.pdf
 
Transport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MITransport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MI
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automation
 
Tetracrom printing process for packaging with CMYK+
Tetracrom printing process for packaging with CMYK+Tetracrom printing process for packaging with CMYK+
Tetracrom printing process for packaging with CMYK+
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdfHCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Automation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions managementAutomation Ops Series: Session 3 - Solutions management
Automation Ops Series: Session 3 - Solutions management
 

CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue

  • 1. Healthy Code January - 2015 14 Code Jugalbandi Article Ryan Dhaval
  • 2. Healthy Code January - 2015 15 Jugalbandi inspires and fuels our desire to learn by focusing on dialogue and exploration. More languages in the room meant more perspectives too. Exploring a paradigm through any single language could. Above all, Code Jugalbandi is a Creator and Listener We met regularly over a period of several months, exploring some key issues related to Functional Programming (FP). This culminated in a live Code Jugalbandi at the Functional Conference in Bengaluru, 2014. During the FP Code Jugalbandi, we explored nine themes, which became melodies. Similar to the musical Jugalbandi, there are two roles: creator and listener. We called the creator of the melody Bramha and the one who listens and responds Krishna explore one such melody: The Expression Problem. The Expression Problem The Expression Problem was coined by Philip Wadler. Wikipedia states that the goal of the Expression Problem is to cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g. no casts). According to Wadler, “Whether a language can solve the Expression Problem is a salient indicator of its capacity for expression.” The Expression Problem - Clojure BRAMHA: In OOP, we model our domain concepts by creating our own types i.e., using classes and interfaces. In a geometric shape, say the Circle, in Clojure. (defrecord Circle [radius]) (Circle. 11) (:radius (Circle. 11)) BRAMHA: Classes in OO act as containers for structured data, as well as behaviour acting on the structured data. In Clojure, records just take care of the structure. BRAMHA: In Clojure, the corollary of an Interface is a Protocol: (defprotocol Shape (area [shape]) (perimeter [shape])) BRAMHA: We can extend our Circle type to implement the Shape protocol, e.g. (extend-type Circle Shape (area [circle] (* (:r circle) (:r circle) Math/PI))) BRAMHA: At this stage we have a simple type-based dispatch for our protocol method area. Clojure is more powerful but less performant polymorphic dispatch through multimethods. (area (Circle. 10)) (area (Rect. 10 20)) BRAMHA something like this: (EP1) create a new type that implements an existing interface BRAMHA our existing Shape protocol: (defrecord Rect [length width] Shape (area [rect] (* (:length rect) (:width rect)))) KRISHNA allow you to create new classes to implement existing BRAMHA: Yes, agreed, but the second part of the Expression Problem is harder to solve in some OO languages: (EP2) implement a new interface for an existing type Moreover (EP1) and (EP2) should be possible without having in working with third party code that you cannot recompile. To achieve (EP2) with Clojure we can do this: (defprotocol Graphic (draw [this])) (extend-type Circle Graphic (draw [this] (puts “O”))) KRISHNA: Clojure fares well with both (EP1) and (EP2). Let me show you how Scala addresses the Expression Problem. The Expression Problem - Scala KRISHNA: We start by creating the Circle and Rectangle as data classes.
  • 3. Healthy Code January - 2015 16 case class Circle(r: Int) case class Rectangle(l: Int, w: Int) KRISHNA Shape that I can perform on Circle and Rectangle. trait Shape[T] { def area(t: T): Double def perimeter(t: T): Double } Then I implement the trait for Circle, say, implicit object CircleOps extends Shape[Circle] { def area(c: Circle): Double = Math.PI * c.r * c.r def perimeter(c: Circle): Double = 2 * Math.PI * c.r } KRISHNA def area[T](t: T)(implicit s: Shape[T]): Double = s.area(t) def perimeter[T](t: T)(implicit s: Shape[T]): Double = s.perimeter(t) KRISHNA: Returning to the Expression Problem, we can solve (EP2) like this in Scala: trait Graphics[T] { def draw(t: T): Unit } implicit object CircleGraphics extends Graphics[Circle] { def draw(c: Circle) = println(“O”) } def draw[T](t: T)(implicit g: Graphics[T]) = g.draw(t) KRISHNA a new Right Triangle type and implement the existing interfaces. case class RTriangle(b: Int, h: Int) import Math._ implicit object RTriangleOps extends Shape[RTriangle] with Graphics[RTriangle] { def area(rt: RTriangle) = 0.5 * rt.b * rt.h def perimeter(rt: RTriangle) = rt.b + rt.h + (sqrt(pow(rt.b, 2) + pow(rt.h, 2)) def draw(rt: RTriangle) = println(rt) } BRAHMA: Scala solves both (EP1) and (EP2), albeit with some syntactic noise around the use of implicit objects. Let me show you how concise Haskell is at solving the Expression Problem. The Expression Problem - Haskell BRAMHA with a few sub-types: data Shape = Circle {radius :: Float} | Rect {length :: Float, width ::Float} deriving Show BRAMHA: To create an area method that is polymorphic over the Shape sub-types: area :: Shape -> Float area (Circle r) = 3.14 * r^2 area (Rect l w) = l * w BRAMHA In (EP1) adding a new sub-type to the Shape algebraic type would require adding a clause for the new subtype to each function I declared over the type (implying a recompile), In (EP2) adding a new function acting on existing algebraic types is trivial. The Expression Problem with TypeClasses Instead of unifying the concepts Circle and Rect as the Shape abstract data type, we could use Haskell typeclasses to unify to not name clash with the above code). data Circle_ = Circle_ {radius_ :: Float} data Rect_ = Rect_ {length_ :: Float, width_ :: Float} class Shape_ a where area_ :: a -> Float perimeter_ :: a -> Float
  • 4. Healthy Code January - 2015 17 BRAMHA: Adding a new data type that implements an existing typeclass is easy (EP1): instance Shape_ Circle_ where area_ (Circle_ r) = pi * r^2 perimeter_(Circle_ r) = 2 * pi * r Extending an existing type with a new interface is simple too (EP2): class Graphics_ a where draw_ :: a -> IO () instance Graphics_ Circle_ where draw_ (Circle_ r) = putStrLn (show r) KRISHNA: In OOP classes, we can combine type with a clear separation between type and behaviour. BRAMHA is that objects contain mutable state. In FP languages, we use immutable values in place of mutable state. For example, the Circle and Rect in all three languages were some form of KRISHNA: The Expression Problem also asks that you can extend types with interfaces without needing to recompile the code you are extending. Our three languages are quite BRAMHA: Scala is more strictly typed, but also fares well by allowing extension of code without recompiling it. If we look, both the Scala and Clojure both resemble Haskell in the KRISHNA: Yes, and Haskell deals with types in a sophisticated yet simple way, but it is less dynamic and more limited in solving this aspect of the (EP). BRAMHA KRISHNA than traditional OO does, but then again, many OO languages have evolved and are much more dynamic these days. In fact, using Java Generics, the Expression Problem can be solved, except that it would be syntactically very noisy Ryan is a software developer, coach and advisor, based in Cape Town. He has been working with code for more than 15 years. Ryan assists individuals and teams to manage the evolution and complexity of their software systems. Ryan is a passionate learner and enjoys facilitating learning in others. Dhavalahands-ondeveloperand mentor, believes that software then a craft. For him writing software brings his creativity to the fore. His interests are in architecting applications ground up, estabilishing environments, transitioning and orienting teams to Agile way of working by embedding himself within teams. CodeJugalbandi object BRAHMA: True, and besides, there are very few purely FP or OO languages. Still, we can say that FP does have good answers to the (EP). References Learn more from