CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015

Dhaval Dalal
Dhaval DalalSoftware Artisan/Agile Coach

The second article in the series Code Jugalbandi in HealthyCode Magazine. This time we are exploring Functional Programming with Sequencing melody. What is Code Jugalbandi? Check out http://codejugalbandi.org

Healthy Code
February - 2015
12
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?”
Article|-------------|Dhaval and Ryan
Code
Jugalbandi
Healthy Code
February - 2015
13
This led to the first Code Jugalbandi between us. Code
Jugalbandi inspired and fuelled our learning by focussing
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!
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 expression
problem. This time we will look at Sequencing.
The Sequencing Problem
Lets say we have a sentence and we want to capitalise words
that have size less than or equal to 3.
Sequencing - Ruby
Bramha: In Ruby, in an imperative style, with mutation of
variables, it would look like this
words = “all mimsy were the borogoves”
split_words = words.split(“s”)
caps_words = []
split_words.each do |w|
;; enumeration and filtering
cap-words.push(w.capitalize) if (w.size < 3)
end
words_s = caps_words.join(“n”)
Bramha: In the above code, enumeration and filtering are
interleaved. Let’s try and separate enumeration and filtering.
words = “all mimsy were the borogoves”
words.split(“s”).map do |w|
w.capitalize
end.filter do |w|
(w.size < 3)
end.join (“n”)
Bramha: This feels a bit more structured, we’re chaining
operations, one after the other. This style is called sequencing,
where we’re moving data down processing pipelines.
Sequencing - Clojure
Bramha: In Clojure, we could chain functions together
through function nesting.
(def words “all mimsy were the borogoves”)
(def using-nesting
(join “n”
(filter (fn [s] (< 3 (count s)))
(map capitalize
(split words #”s”)))))
(println using-nesting)
Bramha: This is hard to understand. Deep nesting leads to
many parentheses in Clojure that is considered a code smell
in Clojure. Let’s try and lose a few parenthesis through
function composition.
(def using-composition
(let [f (comp
(partial join “n”)
(partial filter (fn [s] (< 3 (count s))))
(partial map capitalize)
(fn [s] (split s #”s”)))]
(f words)))
(println using-composition)
Bramha: The awkward thing about these styles of coding
is that the order of functions seem back to front. The arrow
syntax sidesteps composition in lieu of a threading-macro.
(def using-arrow
(->> (split words #”s”)
(map capitalize)
(filter (fn [s] (< 3 (count s))))
(join “n”)))
(println using-arrow)
Krishna: BTW, why is it called a threading-macro in Clojure?
The threading word in there makes me think of process
threads.
Brahma: The word threading is used in the sense of threading
a needle through cloth, not to be confused with process
threads! Since it is implemented as a macro, is is called a
threading-macro.
Sequencing - Scala
Krishna: Lets see that how can we achieve the same in Scala.
Healthy Code
February - 2015
14
Krishna: Now, I’ll define a few function types.
val split = (s: String) => s.split(“ “)
val capitalize = (ws: Array[String]) => ws.map(_.
toUpperCase)
val filter = (ws: Array[String]) => ws.filter(_.size
<= 3)
val join = (ws: Array[String]) => ws mkString “n”
val seqCapitalized = join compose filter compose
capitalize compose split
seqCapitalized (words)
Krishna: Just like in Clojure nesting and composition
examples, this is flowing against the grain of thought.
Let me have the cake and eat it too. I can make use of
Scala’s andThen.
val seqAndThened = split andThen capitalize andThen
filter
andThen join
seqAndThened (words)
Sequencing - Groovy
Krishna: In Groovy too, one can quickly define closures like
this.
def split = { s -> s.split(‘ ‘) as List }
def capitalize = { ws -> ws.collect
{ it.toUpperCase() } }
def filter = { ws -> ws.findAll
{ it.length() <= 3 } }
def join = { ws -> ws.join(‘n’) }
def seqComposed = join << filter << capitalize << split
println (seqComposed(sentence))
def seqAndThened = split >> capitalize >> filter >> join
println (seqAndThened(sentence))
Sequencing - Racket
Brahma: In Racket, one can achieve this using Rackjure (a
Clojure inspired ideas in Racket by Greg Hendershott,http://
www.greghendershott.com/rackjure).
(require racket/string)
(define s “All mimsy were the borogoves”)
(define (capitalize s) (map (λ (w) (string-upcase
w)) s))
(define (words<=3 s) (filter (λ (w) (<= (string-length
w) 3)) s)) (define (sentence->words s) (string-split
s))
(define (join-words ws) (string-join ws))
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
I’ll first show using chaining.
val words = “all mimsy were the borogoves”
println(words
.split(“ “)
.map(w => w.toUpperCase)
.filter(w => w.length <= 3)
.mkString(“n”))
Healthy Code
February - 2015
15
(define sentence-with-3-words
(compose join-words capitalize words<=3 sentence-
>words)) (sentence-with-3-words s)
; using threading from Rackjure
(require rackjure)
(require rackjure/threading)
(~> s sentence->words words<=3 capitalize join-
words)
Reflections
Bramha: In whatever functional programming language
you’re using, if you find yourself deeply nesting functions,
you can be sure there is a better way of “threading” functions
together. Moreover, if you are going against the “grain of
thought”, look for a way in the language to go with the grain!
Krishna: This style is also known as concatenative
programming where function composition is the default way
to build subroutines. Functions written in concatenative style
neither represent argument types nor the names or identifiers
they work with; instead they are just function names laid
out as a pipeline, in such a way that the output type of one
function aligns with the input type of the next function in the
sequence. In this way the order of function application gets
transformed into order of function composition.
Bramha: One of the immediate benefits of this style is that it
makes the code more succinct and readable. We can express
some domain processes very clearly in this way, and we can
easily extract sub-sequences into new functions to further
clarify our statements about the domain.
Krishna:Thisstyle is useful wheneverwe areprocessingdata
through a sequence of transformations, and it is surprising
how much of our domain code is trying to do just this!
References
Learn more from http://codejugalbandi.org
Publisher:
T. Sivasubramanian
Editor:
S. Prabhu
Production:
New Horizon Media Private Limited
Proof Reader:
Shweta Gandhi
Publication Address:
11/6, First Floor,
Fourth Street,
Padmanabha Nagar,
Adyar, Chennai - 600020
Printer: Sakthi Scanners (P) Ltd
7, Dams Road, Chindadripet,
Chennai - 600002.
Contact Phone Number: 044-42337379
Email:
siva@healthycodemagazine.com
Web Site:
http://healthycodemagazine.com
Price: Rs. 150 /-
Healthy Code
February 2015
Vol 1 | Issue 11
Disclaimer:
The articles and contents of the Healthy Code magazine
are sourced directly from the authors with their
permission. Healthy Code doesn’t assume responsibility
for violation of any copyright issues by an author in
their respective article. We have made sure to the best
of our knowledge that the articles and code presented
here are without any errors. However, we can’t be held
liable for any damage or loss that may arise from using
these.
- Publisher

Recommended

4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015 by
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr20154-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015Dhaval Dalal
953 views4 slides
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015 by
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar20153-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015Dhaval Dalal
642 views4 slides
Oo ps exam answer2 by
Oo ps exam answer2Oo ps exam answer2
Oo ps exam answer2Kaushal Vaishnav
218 views3 slides
Approaching Rich Internet Applications by
Approaching Rich Internet ApplicationsApproaching Rich Internet Applications
Approaching Rich Internet ApplicationsDhaval Dalal
1.9K views16 slides
Code jugalbandi by
Code jugalbandiCode jugalbandi
Code jugalbandiDhaval Dalal
774 views2 slides
Transition contours by
Transition contoursTransition contours
Transition contoursDhaval Dalal
2.1K views7 slides

More Related Content

Viewers also liked

Web sockets primer by
Web sockets primerWeb sockets primer
Web sockets primerDhaval Dalal
2.7K views22 slides
The tao-of-transformation by
The tao-of-transformationThe tao-of-transformation
The tao-of-transformationDhaval Dalal
2K views72 slides
Domain languageacceptancetests by
Domain languageacceptancetestsDomain languageacceptancetests
Domain languageacceptancetestsDhaval Dalal
632 views15 slides
C# for-java-developers by
C# for-java-developersC# for-java-developers
C# for-java-developersDhaval Dalal
1.9K views39 slides
Calculator stories by
Calculator storiesCalculator stories
Calculator storiesDhaval Dalal
6.1K views12 slides
Jumping-with-java8 by
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
6.4K views175 slides

Viewers also liked(13)

Web sockets primer by Dhaval Dalal
Web sockets primerWeb sockets primer
Web sockets primer
Dhaval Dalal2.7K views
The tao-of-transformation by Dhaval Dalal
The tao-of-transformationThe tao-of-transformation
The tao-of-transformation
Dhaval Dalal2K views
Domain languageacceptancetests by Dhaval Dalal
Domain languageacceptancetestsDomain languageacceptancetests
Domain languageacceptancetests
Dhaval Dalal632 views
C# for-java-developers by Dhaval Dalal
C# for-java-developersC# for-java-developers
C# for-java-developers
Dhaval Dalal1.9K views
Calculator stories by Dhaval Dalal
Calculator storiesCalculator stories
Calculator stories
Dhaval Dalal6.1K views
Jumping-with-java8 by Dhaval Dalal
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
Dhaval Dalal6.4K views
A case-for-graph-db by Dhaval Dalal
A case-for-graph-dbA case-for-graph-db
A case-for-graph-db
Dhaval Dalal2.1K views
Midas - on-the-fly schema migration tool for MongoDB. by Dhaval Dalal
Midas - on-the-fly schema migration tool for MongoDB.Midas - on-the-fly schema migration tool for MongoDB.
Midas - on-the-fly schema migration tool for MongoDB.
Dhaval Dalal9.7K views
Grooming with Groovy by Dhaval Dalal
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
Dhaval Dalal4.1K views
Math works kids-game by Dhaval Dalal
Math works kids-gameMath works kids-game
Math works kids-game
Dhaval Dalal1.8K views
DRYing to Monad in Java8 by Dhaval Dalal
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal14.1K views

Similar to CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015

Parallel-Ready Java Code: Managing Mutation in an Imperative Language by
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageParallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageMaurice Naftalin
1.3K views212 slides
Visual And Functional Programing Principles by
Visual And Functional Programing PrinciplesVisual And Functional Programing Principles
Visual And Functional Programing PrinciplesKatreka Howard
2 views45 slides
Srikanth CV - BDM by
Srikanth CV - BDMSrikanth CV - BDM
Srikanth CV - BDMsrikanth veldandi
732 views6 slides
Examples Of Oral Presentation by
Examples Of Oral PresentationExamples Of Oral Presentation
Examples Of Oral PresentationLaura Arrigo
4 views86 slides
Graphql by
GraphqlGraphql
GraphqlNeven Rakonić
171 views50 slides
Rails Gems realize RESTful modeling patterns by
Rails Gems realize RESTful modeling patternsRails Gems realize RESTful modeling patterns
Rails Gems realize RESTful modeling patternsToru Kawamura
6.8K views74 slides

Similar to CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015(20)

Parallel-Ready Java Code: Managing Mutation in an Imperative Language by Maurice Naftalin
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageParallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative Language
Maurice Naftalin1.3K views
Visual And Functional Programing Principles by Katreka Howard
Visual And Functional Programing PrinciplesVisual And Functional Programing Principles
Visual And Functional Programing Principles
Katreka Howard2 views
Examples Of Oral Presentation by Laura Arrigo
Examples Of Oral PresentationExamples Of Oral Presentation
Examples Of Oral Presentation
Laura Arrigo4 views
Rails Gems realize RESTful modeling patterns by Toru Kawamura
Rails Gems realize RESTful modeling patternsRails Gems realize RESTful modeling patterns
Rails Gems realize RESTful modeling patterns
Toru Kawamura6.8K views
Creating Community at WeWork through Graph Embeddings with node2vec - Karry Lu by Rising Media Ltd.
Creating Community at WeWork through Graph Embeddings with node2vec - Karry LuCreating Community at WeWork through Graph Embeddings with node2vec - Karry Lu
Creating Community at WeWork through Graph Embeddings with node2vec - Karry Lu
Rising Media Ltd.107.8K views
Souvenir's Booth - Algorithm Design and Analysis Project Project Report by Akshit Arora
Souvenir's Booth - Algorithm Design and Analysis Project Project ReportSouvenir's Booth - Algorithm Design and Analysis Project Project Report
Souvenir's Booth - Algorithm Design and Analysis Project Project Report
Akshit Arora2.6K views
Optimal Clustering Technique for Handwritten Nandinagari Character Recognition by Editor IJCATR
Optimal Clustering Technique for Handwritten Nandinagari Character RecognitionOptimal Clustering Technique for Handwritten Nandinagari Character Recognition
Optimal Clustering Technique for Handwritten Nandinagari Character Recognition
Editor IJCATR158 views
BDX 2016 - Tzach zohar @ kenshoo by Ido Shilon
BDX 2016 - Tzach zohar  @ kenshooBDX 2016 - Tzach zohar  @ kenshoo
BDX 2016 - Tzach zohar @ kenshoo
Ido Shilon478 views
Mobile Distributed Systems For Secure Communication Essay by Susan Kennedy
Mobile Distributed Systems For Secure Communication EssayMobile Distributed Systems For Secure Communication Essay
Mobile Distributed Systems For Secure Communication Essay
Susan Kennedy3 views
CrossLanguageSpotter: A Library for Detecting Relations in Polyglot Frameworks by Giuseppe Rizzo
CrossLanguageSpotter: A Library for Detecting Relations in Polyglot FrameworksCrossLanguageSpotter: A Library for Detecting Relations in Polyglot Frameworks
CrossLanguageSpotter: A Library for Detecting Relations in Polyglot Frameworks
Giuseppe Rizzo829 views
Discovering User's Topics of Interest in Recommender Systems by Gabriel Moreira
Discovering User's Topics of Interest in Recommender SystemsDiscovering User's Topics of Interest in Recommender Systems
Discovering User's Topics of Interest in Recommender Systems
Gabriel Moreira6.1K views
Enterprise Data Workflows with Cascading and Windows Azure HDInsight by Paco Nathan
Enterprise Data Workflows with Cascading and Windows Azure HDInsightEnterprise Data Workflows with Cascading and Windows Azure HDInsight
Enterprise Data Workflows with Cascading and Windows Azure HDInsight
Paco Nathan2.2K views
Data modeling with neo4j tutorial by Max De Marzi
Data modeling with neo4j tutorialData modeling with neo4j tutorial
Data modeling with neo4j tutorial
Max De Marzi3.5K views
OOScss Architecture For Rails Apps by Netguru
OOScss Architecture For Rails AppsOOScss Architecture For Rails Apps
OOScss Architecture For Rails Apps
Netguru753 views

More from Dhaval Dalal

Test Pyramid in Microservices Context by
Test Pyramid in Microservices ContextTest Pyramid in Microservices Context
Test Pyramid in Microservices ContextDhaval Dalal
225 views27 slides
Code Retreat by
Code RetreatCode Retreat
Code RetreatDhaval Dalal
140 views14 slides
Booting into functional programming by
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
2.6K views72 slides
Currying and Partial Function Application (PFA) by
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
2.8K views30 slides
Creating Lazy stream in CSharp by
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharpDhaval Dalal
2.9K views52 slides
Json Viewer Stories by
Json Viewer StoriesJson Viewer Stories
Json Viewer StoriesDhaval Dalal
286 views10 slides

More from Dhaval Dalal(15)

Test Pyramid in Microservices Context by Dhaval Dalal
Test Pyramid in Microservices ContextTest Pyramid in Microservices Context
Test Pyramid in Microservices Context
Dhaval Dalal225 views
Booting into functional programming by Dhaval Dalal
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal2.6K views
Currying and Partial Function Application (PFA) by Dhaval Dalal
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
Dhaval Dalal2.8K views
Creating Lazy stream in CSharp by Dhaval Dalal
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal2.9K views
Mars rover-extension by Dhaval Dalal
Mars rover-extensionMars rover-extension
Mars rover-extension
Dhaval Dalal346 views
How Is Homeopathy Near To Yoga? by Dhaval Dalal
How Is Homeopathy Near To Yoga?How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?
Dhaval Dalal1.8K views
Approaching ATDD/BDD by Dhaval Dalal
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDD
Dhaval Dalal619 views
Paradigms Code jugalbandi by Dhaval Dalal
Paradigms Code jugalbandiParadigms Code jugalbandi
Paradigms Code jugalbandi
Dhaval Dalal1.7K views
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue by Dhaval Dalal
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-IssueCodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
Dhaval Dalal584 views
Healthy Code Magazine June-2014 Issue Midas-Touch-Article by Dhaval Dalal
Healthy Code Magazine June-2014 Issue Midas-Touch-ArticleHealthy Code Magazine June-2014 Issue Midas-Touch-Article
Healthy Code Magazine June-2014 Issue Midas-Touch-Article
Dhaval Dalal477 views
Neo4j MySql MS-SQL comparison by Dhaval Dalal
Neo4j MySql MS-SQL comparisonNeo4j MySql MS-SQL comparison
Neo4j MySql MS-SQL comparison
Dhaval Dalal3.3K views

Recently uploaded

The Role of Patterns in the Era of Large Language Models by
The Role of Patterns in the Era of Large Language ModelsThe Role of Patterns in the Era of Large Language Models
The Role of Patterns in the Era of Large Language ModelsYunyao Li
85 views65 slides
Business Analyst Series 2023 - Week 4 Session 8 by
Business Analyst Series 2023 -  Week 4 Session 8Business Analyst Series 2023 -  Week 4 Session 8
Business Analyst Series 2023 - Week 4 Session 8DianaGray10
123 views13 slides
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc
170 views29 slides
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT by
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITShapeBlue
206 views8 slides
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...ShapeBlue
194 views62 slides
The Power of Heat Decarbonisation Plans in the Built Environment by
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built EnvironmentIES VE
79 views20 slides

Recently uploaded(20)

The Role of Patterns in the Era of Large Language Models by Yunyao Li
The Role of Patterns in the Era of Large Language ModelsThe Role of Patterns in the Era of Large Language Models
The Role of Patterns in the Era of Large Language Models
Yunyao Li85 views
Business Analyst Series 2023 - Week 4 Session 8 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 8Business Analyst Series 2023 -  Week 4 Session 8
Business Analyst Series 2023 - Week 4 Session 8
DianaGray10123 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc170 views
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT by ShapeBlue
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBITUpdates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
Updates on the LINSTOR Driver for CloudStack - Rene Peinthor - LINBIT
ShapeBlue206 views
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P... by ShapeBlue
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
Developments to CloudStack’s SDN ecosystem: Integration with VMWare NSX 4 - P...
ShapeBlue194 views
The Power of Heat Decarbonisation Plans in the Built Environment by IES VE
The Power of Heat Decarbonisation Plans in the Built EnvironmentThe Power of Heat Decarbonisation Plans in the Built Environment
The Power of Heat Decarbonisation Plans in the Built Environment
IES VE79 views
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue by ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlueCloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
CloudStack Object Storage - An Introduction - Vladimir Petrov - ShapeBlue
ShapeBlue138 views
Why and How CloudStack at weSystems - Stephan Bienek - weSystems by ShapeBlue
Why and How CloudStack at weSystems - Stephan Bienek - weSystemsWhy and How CloudStack at weSystems - Stephan Bienek - weSystems
Why and How CloudStack at weSystems - Stephan Bienek - weSystems
ShapeBlue238 views
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue by ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlueWhat’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
What’s New in CloudStack 4.19 - Abhishek Kumar - ShapeBlue
ShapeBlue263 views
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading... by The Digital Insurer
Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...Webinar : Desperately Seeking Transformation - Part 2:  Insights from leading...
Webinar : Desperately Seeking Transformation - Part 2: Insights from leading...
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue222 views
NTGapps NTG LowCode Platform by Mustafa Kuğu
NTGapps NTG LowCode Platform NTGapps NTG LowCode Platform
NTGapps NTG LowCode Platform
Mustafa Kuğu423 views
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue180 views
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue by ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlueMigrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
Migrating VMware Infra to KVM Using CloudStack - Nicolas Vazquez - ShapeBlue
ShapeBlue218 views
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates by ShapeBlue
Keynote Talk: Open Source is Not Dead - Charles Schulz - VatesKeynote Talk: Open Source is Not Dead - Charles Schulz - Vates
Keynote Talk: Open Source is Not Dead - Charles Schulz - Vates
ShapeBlue252 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue203 views
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue by ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlueCloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
CloudStack Managed User Data and Demo - Harikrishna Patnala - ShapeBlue
ShapeBlue135 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue161 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue119 views

CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015

  • 1. Healthy Code February - 2015 12 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?” Article|-------------|Dhaval and Ryan Code Jugalbandi
  • 2. Healthy Code February - 2015 13 This led to the first Code Jugalbandi between us. Code Jugalbandi inspired and fuelled our learning by focussing 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! 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 expression problem. This time we will look at Sequencing. The Sequencing Problem Lets say we have a sentence and we want to capitalise words that have size less than or equal to 3. Sequencing - Ruby Bramha: In Ruby, in an imperative style, with mutation of variables, it would look like this words = “all mimsy were the borogoves” split_words = words.split(“s”) caps_words = [] split_words.each do |w| ;; enumeration and filtering cap-words.push(w.capitalize) if (w.size < 3) end words_s = caps_words.join(“n”) Bramha: In the above code, enumeration and filtering are interleaved. Let’s try and separate enumeration and filtering. words = “all mimsy were the borogoves” words.split(“s”).map do |w| w.capitalize end.filter do |w| (w.size < 3) end.join (“n”) Bramha: This feels a bit more structured, we’re chaining operations, one after the other. This style is called sequencing, where we’re moving data down processing pipelines. Sequencing - Clojure Bramha: In Clojure, we could chain functions together through function nesting. (def words “all mimsy were the borogoves”) (def using-nesting (join “n” (filter (fn [s] (< 3 (count s))) (map capitalize (split words #”s”))))) (println using-nesting) Bramha: This is hard to understand. Deep nesting leads to many parentheses in Clojure that is considered a code smell in Clojure. Let’s try and lose a few parenthesis through function composition. (def using-composition (let [f (comp (partial join “n”) (partial filter (fn [s] (< 3 (count s)))) (partial map capitalize) (fn [s] (split s #”s”)))] (f words))) (println using-composition) Bramha: The awkward thing about these styles of coding is that the order of functions seem back to front. The arrow syntax sidesteps composition in lieu of a threading-macro. (def using-arrow (->> (split words #”s”) (map capitalize) (filter (fn [s] (< 3 (count s)))) (join “n”))) (println using-arrow) Krishna: BTW, why is it called a threading-macro in Clojure? The threading word in there makes me think of process threads. Brahma: The word threading is used in the sense of threading a needle through cloth, not to be confused with process threads! Since it is implemented as a macro, is is called a threading-macro. Sequencing - Scala Krishna: Lets see that how can we achieve the same in Scala.
  • 3. Healthy Code February - 2015 14 Krishna: Now, I’ll define a few function types. val split = (s: String) => s.split(“ “) val capitalize = (ws: Array[String]) => ws.map(_. toUpperCase) val filter = (ws: Array[String]) => ws.filter(_.size <= 3) val join = (ws: Array[String]) => ws mkString “n” val seqCapitalized = join compose filter compose capitalize compose split seqCapitalized (words) Krishna: Just like in Clojure nesting and composition examples, this is flowing against the grain of thought. Let me have the cake and eat it too. I can make use of Scala’s andThen. val seqAndThened = split andThen capitalize andThen filter andThen join seqAndThened (words) Sequencing - Groovy Krishna: In Groovy too, one can quickly define closures like this. def split = { s -> s.split(‘ ‘) as List } def capitalize = { ws -> ws.collect { it.toUpperCase() } } def filter = { ws -> ws.findAll { it.length() <= 3 } } def join = { ws -> ws.join(‘n’) } def seqComposed = join << filter << capitalize << split println (seqComposed(sentence)) def seqAndThened = split >> capitalize >> filter >> join println (seqAndThened(sentence)) Sequencing - Racket Brahma: In Racket, one can achieve this using Rackjure (a Clojure inspired ideas in Racket by Greg Hendershott,http:// www.greghendershott.com/rackjure). (require racket/string) (define s “All mimsy were the borogoves”) (define (capitalize s) (map (λ (w) (string-upcase w)) s)) (define (words<=3 s) (filter (λ (w) (<= (string-length w) 3)) s)) (define (sentence->words s) (string-split s)) (define (join-words ws) (string-join ws)) 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 I’ll first show using chaining. val words = “all mimsy were the borogoves” println(words .split(“ “) .map(w => w.toUpperCase) .filter(w => w.length <= 3) .mkString(“n”))
  • 4. Healthy Code February - 2015 15 (define sentence-with-3-words (compose join-words capitalize words<=3 sentence- >words)) (sentence-with-3-words s) ; using threading from Rackjure (require rackjure) (require rackjure/threading) (~> s sentence->words words<=3 capitalize join- words) Reflections Bramha: In whatever functional programming language you’re using, if you find yourself deeply nesting functions, you can be sure there is a better way of “threading” functions together. Moreover, if you are going against the “grain of thought”, look for a way in the language to go with the grain! Krishna: This style is also known as concatenative programming where function composition is the default way to build subroutines. Functions written in concatenative style neither represent argument types nor the names or identifiers they work with; instead they are just function names laid out as a pipeline, in such a way that the output type of one function aligns with the input type of the next function in the sequence. In this way the order of function application gets transformed into order of function composition. Bramha: One of the immediate benefits of this style is that it makes the code more succinct and readable. We can express some domain processes very clearly in this way, and we can easily extract sub-sequences into new functions to further clarify our statements about the domain. Krishna:Thisstyle is useful wheneverwe areprocessingdata through a sequence of transformations, and it is surprising how much of our domain code is trying to do just this! References Learn more from http://codejugalbandi.org Publisher: T. Sivasubramanian Editor: S. Prabhu Production: New Horizon Media Private Limited Proof Reader: Shweta Gandhi Publication Address: 11/6, First Floor, Fourth Street, Padmanabha Nagar, Adyar, Chennai - 600020 Printer: Sakthi Scanners (P) Ltd 7, Dams Road, Chindadripet, Chennai - 600002. Contact Phone Number: 044-42337379 Email: siva@healthycodemagazine.com Web Site: http://healthycodemagazine.com Price: Rs. 150 /- Healthy Code February 2015 Vol 1 | Issue 11 Disclaimer: The articles and contents of the Healthy Code magazine are sourced directly from the authors with their permission. Healthy Code doesn’t assume responsibility for violation of any copyright issues by an author in their respective article. We have made sure to the best of our knowledge that the articles and code presented here are without any errors. However, we can’t be held liable for any damage or loss that may arise from using these. - Publisher