SlideShare a Scribd company logo
Healthy Code
April - 2015
10
In 2013, Dhaval Dalal was inspired by Jugalbandi, an Indian classical music
form in which musicians have an improvised musical conversation, each using a
different instrument, while exploring a shared musical theme together akin to Jazz
in some ways. Dhaval thought, “What if we could have a conversation about some
programming concepts in this way? Instead of musical instruments, what if we use
different programming languages?”
Code
Jugalbandi
Article
Ryan and Dhaval
Healthy Code
April - 2015
11
Creator and Listener
We met regularly with over a period of several months,
exploring some key issues related to Functional
Programming(FP).ThisculminatedinaliveCodeJugalbandi
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
with a different instrument, Krishna. + In the last Code
Jugalbandi Article, we looked at the melody, the Currying
and Partial Function problem. This time we will look at De-
Structuring and Pattern Matching.
De-structuring
BRAMHA: In FP, we favour simple data structures over
classes, e.g. instead of a collection of people objects, we might
have a collection of person tuples, and containing only the
fields we’re interested in:
//Tuple with 2 elements - name and age
type Person = (String, Int)
val p = ("alan", 30)
BRAMHA: … and then we have some functions acting on
this person data type. Whatever we’ll do with person, we’ll
need code to get at the innards of the person tuple.
def showPerson(p: Person) = p match {
case (name, age) => println(s"$name - $age")
}
showPerson(p) //alan - 30
BRAMHA: How does this look in Clojure?
KRISHNA: Most functional languages provide some level
of de-structuring:
(def a-person ["alan" 30])
(defn print-person [p]
(println (first p) " " (second p)))
(defn print-person2 [[name age]]
(println name " - " age))
KRISHNA: De-structuring gives you a shorthand way of
naming parts of a structure. If we were using a hash-map to
represent our person:
(def h-person {:name "alan"
:age 30 })
;; de-structuring hash-maps looks like this:
(defn print-person3 [{:keys [name age]}]
(println name " - " age))
KRISHNA: There are libraries that allow for even more
compact and sophisticated de-structuring syntax, but let’s
leave it at that for de-structuring in Clojure.
BRAMHA: This is interesting, I am not aware of de-
structuring Maps in Scala, out-of-the-box. However, you can
de-structure Lists, Vectors and Streams in Scala. If Person was
a Vector like you showed in Clojure, I could do the following
val p = List("alan", 30)
def showPerson(p: List[Any]) = p match {
case List(name, age) => println(s"$name - $age")
}
showPerson(p) //alan - 30
This led to the first Code Jugalbandi between us. Code
Jugalbandi inspired and fuelled our learning by focusing
on dialogue and exploration. More languages in the
room meant more perspectives too. Exploring a paradigm
through many languages gave us a better map of the
territory than any single language could. Above all,
Code Jugalbandi was a playful way to learn together!
Healthy Code
April - 2015
12
Pattern Matching
BRAMHA: So far we’ve just talked about picking apart the
structure of things, but we can generalize de-structuring into
something even more powerful: Pattern Matching (not to be
confused with string pattern matching)
BRAMHA: Let’s explore this by example. Say we have a
journal with some fields.
case class Journal(op: String, amt: Double)
BRAMHA: Let’s say, we want to save the journal entries
like debit and credit.
def save(j: Journal) = j match {
case Journal("debit" , _) => println("Debit")
case Journal("credit", _) => println("Credit")
case Journal(_ , _) => println("Unknown")
}
save(Journal("debit", 23)) //Debit
save(Journal("credit", 10)) //Credit
save(Journal("transfer", 50)) //Unknown
KRISHNA: Does the underscore "_" here mean wildcard?
BRAMHA: Yes, it means that we don’t care about it and is
used as a placeholder during pattern matching.
BRAMHA: We get pattern matching in Scala for free by
usingcaseclasses.Scalacompilerimplicitlyaddsacompanion
object for the case class and provides an implementation for
the apply() method (basically factory method to create the
classes) and an unapply() method to get the constituents
back.
KRISHNA: Yes, I see, we want to pick only those journals
where the first value is debit or credit. So, you can’t do this
kind of thing in Clojure.
Pattern Matching - Clojure
KRISHNA: Idiomatic Clojure doesn’t have "Pattern
Matching" in that way. But, there is a way to achieve this
(there are libraries that implement sophisticated Pattern
Matching)
(def debit-journal [:debit 25.4])
(def credit-journal [:credit 26.5])
Then one can use multi-methods in Clojure like this.
(defmulti save-j (fn [j] (first j)))
(defmethod save-j :debit [j]
(println "DEBIT: " j))
(defmethod save-j :credit [j]
(println "CREDIT: " j))
(save-j debit-journal)
(save-j credit-journal)
KRISHNA: Multi-methods allow dispatching on the
arguments in a very flexible way.
Pattern Matching - Haskell
KRISHNA: In Haskell, this would have been expressed
much more directly.
data Journal = Journal String Float
save_j :: Journal -> IO()
save_j (Journal "debit" _ _)
= print ("Debit")
save_j (Journal "credit" _ _)
= print ("Credit")
save_j (Journal _ _ _)
= print ("Unknown")
save_j (Journal "debit" 20.0) —— Debit
save_j (Journal "credit" 100.0) —— Credit
save_j (Journal "transfer" 50.0) —— Unknown
KRISHNA: So, we use pattern matching when we define
a function, that is, embed pattern matching in function
definitions. However, you can also do case distinctions
explicitly, similar to Scala.
save_j :: Journal -> IO()
save_j jrnl = case jrnl of
Journal "debit" _
-> print ("Debit")
Journal "credit" _
-> print ("Credit")
Journal _ _
-> print ("Unknown")
KRISHNA: In Haskell, we can pattern match on tuples as
well.
showPerson :: (String, Int) -> IO()
showPerson (name, age)
= print (name ++ " - " ++ (show age))
showPerson ("alan", 30)
KRISHNA: In Haskell, pattern matching is a deep part of
the language and we have just scratched the surface here.
Reflections
KRISHNA: There is a difference between De-structuring
and Pattern Matching. In pattern matching, we’re not
only matching on relative position of elements in the data
structure, we’re trying to dispatch to different functions
based on a value inside the data structure! This dispatch is
a kind of conditional construct, while with de-structuring
there is nothing conditional about it.
Healthy Code
April - 2015
13
BRAMHA: In Clojure, we saw basic de-structuring, and
then more sophisticated pattern matching made possible
by Multi-method dispatch. In Scala and Haskell, de-
structuring and pattern matching are unified using
the case expressions.
KRISHNA: Pattern matching with all the case distinctions is
like generalization of switch statements in Java/C#, where we
used Ints, Enums etc., but we can now use class hierarchies
or data types. It so happens that the syntax is different.
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
development is first an art and
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.
You can follow them on Twitter @
CodeJugalbandi
“In the old days, people
robbed stagecoaches and
knocked off armored
trucks. Now they’re
knocking off servers.”
- Richard Power
“The inside of a computer
is as dumb as hell but it
goes like mad!”
- Richard Feynman
“The question of whether
computers can think is
just like the question
of whether submarines
can swim.”
- Edsger W. Dijkstra
Pragmatic
Programmer Quote

More Related Content

Similar to 4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015

CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-IssueCodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
Dhaval Dalal
 
DSLs for fun and profit by Jukka Välimaa
DSLs for fun and profit by Jukka VälimaaDSLs for fun and profit by Jukka Välimaa
DSLs for fun and profit by Jukka Välimaa
Montel Intergalactic
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
Peter Solymos
 
More expressive types for spark with frameless
More expressive types for spark with framelessMore expressive types for spark with frameless
More expressive types for spark with frameless
Miguel Pérez Pasalodos
 
03 introduction to graph databases
03   introduction to graph databases03   introduction to graph databases
03 introduction to graph databases
Neo4j
 
Four Languages From Forty Years Ago
Four Languages From Forty Years AgoFour Languages From Forty Years Ago
Four Languages From Forty Years Ago
Scott Wlaschin
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
Mosky Liu
 
Seminar
SeminarSeminar
SEMINAR
SEMINARSEMINAR
Oo ps exam answer2
Oo ps exam answer2Oo ps exam answer2
Oo ps exam answer2
Kaushal Vaishnav
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола Мозговий
Sigma Software
 
Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)
Saurabh Nanda
 
The Geometry of Learning
The Geometry of LearningThe Geometry of Learning
The Geometry of Learning
fridolin.wild
 
Presentation on use of r statistics
Presentation on use of r statisticsPresentation on use of r statistics
Presentation on use of r statistics
Krishna Dhakal
 
Introducing natural language processing(NLP) with r
Introducing natural language processing(NLP) with rIntroducing natural language processing(NLP) with r
Introducing natural language processing(NLP) with r
Vivian S. Zhang
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
Hermann Hueck
 
A fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFsA fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFs
Holden Karau
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 
Ch2
Ch2Ch2
The good parts in scalaz
The good parts in scalazThe good parts in scalaz
The good parts in scalaz
Kobib9
 

Similar to 4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015 (20)

CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-IssueCodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
 
DSLs for fun and profit by Jukka Välimaa
DSLs for fun and profit by Jukka VälimaaDSLs for fun and profit by Jukka Välimaa
DSLs for fun and profit by Jukka Välimaa
 
Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
More expressive types for spark with frameless
More expressive types for spark with framelessMore expressive types for spark with frameless
More expressive types for spark with frameless
 
03 introduction to graph databases
03   introduction to graph databases03   introduction to graph databases
03 introduction to graph databases
 
Four Languages From Forty Years Ago
Four Languages From Forty Years AgoFour Languages From Forty Years Ago
Four Languages From Forty Years Ago
 
Beyond the Style Guides
Beyond the Style GuidesBeyond the Style Guides
Beyond the Style Guides
 
Seminar
SeminarSeminar
Seminar
 
SEMINAR
SEMINARSEMINAR
SEMINAR
 
Oo ps exam answer2
Oo ps exam answer2Oo ps exam answer2
Oo ps exam answer2
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола Мозговий
 
Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)Why is Haskell so hard! (And how to deal with it?)
Why is Haskell so hard! (And how to deal with it?)
 
The Geometry of Learning
The Geometry of LearningThe Geometry of Learning
The Geometry of Learning
 
Presentation on use of r statistics
Presentation on use of r statisticsPresentation on use of r statistics
Presentation on use of r statistics
 
Introducing natural language processing(NLP) with r
Introducing natural language processing(NLP) with rIntroducing natural language processing(NLP) with r
Introducing natural language processing(NLP) with r
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
A fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFsA fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFs
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Ch2
Ch2Ch2
Ch2
 
The good parts in scalaz
The good parts in scalazThe good parts in scalaz
The good parts in scalaz
 

More from Dhaval Dalal

Test Pyramid in Microservices Context
Test Pyramid in Microservices ContextTest Pyramid in Microservices Context
Test Pyramid in Microservices Context
Dhaval Dalal
 
Code Retreat
Code RetreatCode Retreat
Code Retreat
Dhaval Dalal
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval 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 CSharp
Dhaval Dalal
 
Json Viewer Stories
Json Viewer StoriesJson Viewer Stories
Json Viewer Stories
Dhaval Dalal
 
Value Objects
Value ObjectsValue Objects
Value Objects
Dhaval Dalal
 
Mars rover-extension
Mars rover-extensionMars rover-extension
Mars rover-extension
Dhaval 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/BDD
Dhaval Dalal
 
Paradigms Code jugalbandi
Paradigms Code jugalbandiParadigms Code jugalbandi
Paradigms Code jugalbandi
Dhaval Dalal
 
Data Reconciliation
Data ReconciliationData Reconciliation
Data Reconciliation
Dhaval Dalal
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
CodeRetreat
CodeRetreatCodeRetreat
CodeRetreat
Dhaval Dalal
 
The tao-of-transformation-workshop
The tao-of-transformation-workshopThe tao-of-transformation-workshop
The tao-of-transformation-workshop
Dhaval Dalal
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
Dhaval Dalal
 
Language portfolio
Language portfolioLanguage portfolio
Language portfolio
Dhaval Dalal
 
Code jugalbandi
Code jugalbandiCode jugalbandi
Code jugalbandi
Dhaval Dalal
 
A case-for-graph-db
A case-for-graph-dbA case-for-graph-db
A case-for-graph-db
Dhaval Dalal
 
Transition contours
Transition contoursTransition contours
Transition contours
Dhaval 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
 
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
 
A case-for-graph-db
A case-for-graph-dbA case-for-graph-db
A case-for-graph-db
 
Transition contours
Transition contoursTransition contours
Transition contours
 

Recently uploaded

HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015

  • 1. Healthy Code April - 2015 10 In 2013, Dhaval Dalal was inspired by Jugalbandi, an Indian classical music form in which musicians have an improvised musical conversation, each using a different instrument, while exploring a shared musical theme together akin to Jazz in some ways. Dhaval thought, “What if we could have a conversation about some programming concepts in this way? Instead of musical instruments, what if we use different programming languages?” Code Jugalbandi Article Ryan and Dhaval
  • 2. Healthy Code April - 2015 11 Creator and Listener We met regularly with over a period of several months, exploring some key issues related to Functional Programming(FP).ThisculminatedinaliveCodeJugalbandi 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 with a different instrument, Krishna. + In the last Code Jugalbandi Article, we looked at the melody, the Currying and Partial Function problem. This time we will look at De- Structuring and Pattern Matching. De-structuring BRAMHA: In FP, we favour simple data structures over classes, e.g. instead of a collection of people objects, we might have a collection of person tuples, and containing only the fields we’re interested in: //Tuple with 2 elements - name and age type Person = (String, Int) val p = ("alan", 30) BRAMHA: … and then we have some functions acting on this person data type. Whatever we’ll do with person, we’ll need code to get at the innards of the person tuple. def showPerson(p: Person) = p match { case (name, age) => println(s"$name - $age") } showPerson(p) //alan - 30 BRAMHA: How does this look in Clojure? KRISHNA: Most functional languages provide some level of de-structuring: (def a-person ["alan" 30]) (defn print-person [p] (println (first p) " " (second p))) (defn print-person2 [[name age]] (println name " - " age)) KRISHNA: De-structuring gives you a shorthand way of naming parts of a structure. If we were using a hash-map to represent our person: (def h-person {:name "alan" :age 30 }) ;; de-structuring hash-maps looks like this: (defn print-person3 [{:keys [name age]}] (println name " - " age)) KRISHNA: There are libraries that allow for even more compact and sophisticated de-structuring syntax, but let’s leave it at that for de-structuring in Clojure. BRAMHA: This is interesting, I am not aware of de- structuring Maps in Scala, out-of-the-box. However, you can de-structure Lists, Vectors and Streams in Scala. If Person was a Vector like you showed in Clojure, I could do the following val p = List("alan", 30) def showPerson(p: List[Any]) = p match { case List(name, age) => println(s"$name - $age") } showPerson(p) //alan - 30 This led to the first Code Jugalbandi between us. Code Jugalbandi inspired and fuelled our learning by focusing on dialogue and exploration. More languages in the room meant more perspectives too. Exploring a paradigm through many languages gave us a better map of the territory than any single language could. Above all, Code Jugalbandi was a playful way to learn together!
  • 3. Healthy Code April - 2015 12 Pattern Matching BRAMHA: So far we’ve just talked about picking apart the structure of things, but we can generalize de-structuring into something even more powerful: Pattern Matching (not to be confused with string pattern matching) BRAMHA: Let’s explore this by example. Say we have a journal with some fields. case class Journal(op: String, amt: Double) BRAMHA: Let’s say, we want to save the journal entries like debit and credit. def save(j: Journal) = j match { case Journal("debit" , _) => println("Debit") case Journal("credit", _) => println("Credit") case Journal(_ , _) => println("Unknown") } save(Journal("debit", 23)) //Debit save(Journal("credit", 10)) //Credit save(Journal("transfer", 50)) //Unknown KRISHNA: Does the underscore "_" here mean wildcard? BRAMHA: Yes, it means that we don’t care about it and is used as a placeholder during pattern matching. BRAMHA: We get pattern matching in Scala for free by usingcaseclasses.Scalacompilerimplicitlyaddsacompanion object for the case class and provides an implementation for the apply() method (basically factory method to create the classes) and an unapply() method to get the constituents back. KRISHNA: Yes, I see, we want to pick only those journals where the first value is debit or credit. So, you can’t do this kind of thing in Clojure. Pattern Matching - Clojure KRISHNA: Idiomatic Clojure doesn’t have "Pattern Matching" in that way. But, there is a way to achieve this (there are libraries that implement sophisticated Pattern Matching) (def debit-journal [:debit 25.4]) (def credit-journal [:credit 26.5]) Then one can use multi-methods in Clojure like this. (defmulti save-j (fn [j] (first j))) (defmethod save-j :debit [j] (println "DEBIT: " j)) (defmethod save-j :credit [j] (println "CREDIT: " j)) (save-j debit-journal) (save-j credit-journal) KRISHNA: Multi-methods allow dispatching on the arguments in a very flexible way. Pattern Matching - Haskell KRISHNA: In Haskell, this would have been expressed much more directly. data Journal = Journal String Float save_j :: Journal -> IO() save_j (Journal "debit" _ _) = print ("Debit") save_j (Journal "credit" _ _) = print ("Credit") save_j (Journal _ _ _) = print ("Unknown") save_j (Journal "debit" 20.0) —— Debit save_j (Journal "credit" 100.0) —— Credit save_j (Journal "transfer" 50.0) —— Unknown KRISHNA: So, we use pattern matching when we define a function, that is, embed pattern matching in function definitions. However, you can also do case distinctions explicitly, similar to Scala. save_j :: Journal -> IO() save_j jrnl = case jrnl of Journal "debit" _ -> print ("Debit") Journal "credit" _ -> print ("Credit") Journal _ _ -> print ("Unknown") KRISHNA: In Haskell, we can pattern match on tuples as well. showPerson :: (String, Int) -> IO() showPerson (name, age) = print (name ++ " - " ++ (show age)) showPerson ("alan", 30) KRISHNA: In Haskell, pattern matching is a deep part of the language and we have just scratched the surface here. Reflections KRISHNA: There is a difference between De-structuring and Pattern Matching. In pattern matching, we’re not only matching on relative position of elements in the data structure, we’re trying to dispatch to different functions based on a value inside the data structure! This dispatch is a kind of conditional construct, while with de-structuring there is nothing conditional about it.
  • 4. Healthy Code April - 2015 13 BRAMHA: In Clojure, we saw basic de-structuring, and then more sophisticated pattern matching made possible by Multi-method dispatch. In Scala and Haskell, de- structuring and pattern matching are unified using the case expressions. KRISHNA: Pattern matching with all the case distinctions is like generalization of switch statements in Java/C#, where we used Ints, Enums etc., but we can now use class hierarchies or data types. It so happens that the syntax is different. 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 development is first an art and 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. You can follow them on Twitter @ CodeJugalbandi “In the old days, people robbed stagecoaches and knocked off armored trucks. Now they’re knocking off servers.” - Richard Power “The inside of a computer is as dumb as hell but it goes like mad!” - Richard Feynman “The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra Pragmatic Programmer Quote