SlideShare una empresa de Scribd logo
1 de 4
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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 a 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 a 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
 

Más de 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
 

Más de 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
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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