SlideShare a Scribd company logo
1 of 39
DataWeave 2.0
Advanced Concepts - Recursion & Pattern Matching
Joshua Erney
● www.jerney.io (Blog)
● @jerney_io (Twitter)
● www.linkedin.com/in/jerney
Agenda
1. Introduction
2. Quick review of basics
3. Looping / Recursion
a. Tail Call Optimization
4. Pattern Matching
a. By predicate expressions
b. By data type
5. Combined Examples / Demos
a. Use Case 1 - applyToValues
b. Use Case 2 - applyToKeys
6. Questions
Who Am I? Why Should You Listen To Me?!
● Programming since ‘11 (not bragging)
○ Java, Python, JavaScript
● Working w/ MuleSoft products for about 3 years
● Saw no DataWeave experts at my company or in the community at the time, I LOVE learning
programming languages, so decided to focus efforts there
● Started learning DataWeave about the same time Functional Programming started making sense
to me
Disclaimer
I don’t work for MuleSoft, and I’ve never seen the source code for DataWeave. Because of this, I have no
way of knowing with 100% certainty how the language works; DataWeave is a black box to me.
Opinions are my own and do not necessarily reflect those of my employer.
A Quick Review of the Basics
● DataWeave is a domain-specific language created specifically to optimize data transformations
regardless of source and target formats
● Fully-fledged programming language
● Adheres to the core tenets of functional programming, i.e., it is a functional programming language
A Quick Review of the Basics (Cont.)
● Most transformations are done using `map`, `filter`, or `reduce`
○ `map` - transforms elements in an array
○ `filter` - removes elements in an array
○ `reduce` - general purpose tool for doing pretty much anything else with an array. Great for transforming
arrays into objects or scalar values like strings and numbers.
● Data structures in DataWeave are immutable (this restriction is essentially the crux of this talk)
● If you want a deep dive into the basics (highly recommended), you should check out the webinar I
did w/ Manik Magar: https://www.youtube.com/watch?v=r-jjcHPEP34
Iteration, Recursion
Why is iteration part of “Advanced Dataweave”?
● Conceptually, it isn’t, we just don’t need to think about it that much
● DataWeave’s immutable data structures present a barrier to using the iteration techniques
typically used in Java
Iteration in Java (Imperative)
for (i = 0; i < 100; i++) {
System.out.println(i);
}
There are a couple of issues here that make this
style of looping incompatible with DataWeave:
1. i++, this changes the variable i in place,
meaning i is not immutable.
2. System.out.println(i);, we could
put any number of statements with side-
effects in the body of the loop. Other
looping constructs like while have the
same property.
Iteration in DataWeave (Functional)
● We can iterate using one of two strategies:
a. Reduce
b. Recursion
What is recursion?
According to Wikipedia:
Recursion in computer science is a method of solving a problem where the solution depends on
solutions to smaller instances of the same problem (as opposed to iteration).
According to me, for this talk:
Recursion is when a function calls itself for the purposes of looping in DataWeave.
Recursion Example
%dw 2.0
output application/json
var range = 1 to 10
fun recurSum(arr, total=0) =
if not isEmpty(arr)
recurSum(arr[1 to -1], total + arr[0])
else
total
---
recurSum(range) // 1 + 2 + 3 + …, 10 = 45
Dissecting recursion
An Aside: Looping with Reduce
Most of the times when you’re looping with recursion to get from an array to a single value, it’s better
(and safer) to use `reduce`. Here’s the previous example using recursion instead:
fun recurSum(arr) =
arr reduce (n, total=0) -> total + n
If you can use `reduce` instead of recursion, you should do so.
A Problem with Recursion
● If you’re not careful, and/or your language does not support tail call optimization, you can run out
of memory. This results in a stack overflow
● Tail call optimization is an optimization that the language implementation makes so that recursion
is implemented as iteration, so that it doesn’t blow the stack
● Tail call optimization is supported in DataWeave since 2.0
What is a tail call?
● A tail call is a call to a function that is performed as the final action needed in the function body.
Tail call examples
Tail Call (recurSum is the last call in the function
body)
fun recurSum(arr, total=0) =
if not isEmpty(arr)
recurSum(arr[1 to -1], total +
arr[0])
else
total
Not a Tail Call (function still must add the result of
recurSum to arr[0])
fun recurSum(arr) =
if not isEmpty(arr)
arr[0] + recurSum(arr[1 to -1])
else
0
Pattern Matching
What is Pattern Matching?
Most people think of pattern matching as a much more robust switch statement. It’s really important to
know that `match` is not a statement, it is an expression, and therefore evaluates to a value. In
DataWeave, we use the `match`, `case`, and `else` keywords to perform pattern matching, and it can
perform much like a switch statement (but again, it returns):
“Hello” match {
case “Hello” -> “World!”
case “Goodbye” -> “Space!”
else -> “Where am I?”
}
// Returns “World!”
What else can we match on?
We’re not just limited to strings, we can match on
1. any literals (booleans, numbers, etc),
2. predicate expressions
3. type
4. regex (we won’t go over this, its use will be intuitive after going over the other matchables)
Matching on Predicate Expressions
● A predicate expression is an expression that evaluates to true or false
● With `match`, this predicate expression usually takes the form `if <boolean test>`
● When using predicate expressions with `match`, `match` will match with the first predicate
expression that evaluates to true, and ignore the rest
● With predicate expressions, you need to specify the name that the value to match will be referred
to in the predicate expression (this is always an option, even though it was not shown in the
previous example)
Matching on Predicate Expressions (Cont.)
Matching on Type
We can also match on type:
[1,2,3] match {
case is Array -> “We have an array”
case is Object -> “We have an object”
else -> “We have neither an array or object”
}
// Returns “We have an array”
Combining Pattern Matching and
Recursion to Navigate Nested
Data
Use Case 1:
We need a utility function that will modify all of the values in an element, regardless of how deeply
they’re nested.
An element in this case is either an Object, Array, or any combination of the two.
How do we approach this?
Use Case 1: Approach
● We want to write a function that can be reused among ANY use case that needs the same behavior
● The use case doesn’t specify what modification should take place, so our function should probably
take another function as a parameter that describes this behavior, instead of hard-coding it
● We need to determine a way to navigate through a series of ambiguously nested elements, or
potentially no nesting at all (e.g. 1-dimensional array)
Use Case 1: Function Signature
Ultimately, we’re going to want something like this:
applyToValues(
e: Object|Array,
fn: (Scalar) -> Scalar
) -> Object|Array
Please note that Scalar isn’t a DW type, I’m just using it to represent that what gets passed into fn and
that what fn returns should be a single value, not a collection. Strings will classify as Scalar, not
collection of chars.
Use Case 1: Implementation
fun applyToValues(e, fn) =
e match {
case is Array -> e map applyToValues($, fn)
case is Object -> e mapObject {($$): applyToValues($, fn)}
else -> fn(e) // transform value
}
Use Case 1: Notes
While the Array branch of the `match` has the recursive call in tail position, the Object branch of the
`match` does not. Be careful using this on very large elements.
Use Case 2:
We need a utility function that will modify all of the keys in an element, regardless of how deeply they’re
nested.
An element in this case is either an Object, Array, or any combination of the two.
How do we approach this?
Use Case 2: Approach
● We want to write a function that can be reused among ANY use case that needs the same behavior
● The use case doesn’t specify what modification should take place, so our function should probably
take another function as a parameter that describes this behavior, instead of hard-coding it
● We need to determine a way to navigate through a series of ambiguously nested elements, or
potentially no nesting at all (e.g. 1-dimensional array)
Use Case 2: Function Signature
Same as our previous function, but we’ll call it applyToKeys
Use Case 2: Implementation
fun applyToKeys(e, fn) =
e match {
case is Array -> e map applyToKeys($, fn)
case is Object -> e mapObject {(fn($$)): applyToKeys($, fn)}
else -> e // pass through values
}
A Pattern Emerges
Similarities
fun applyToValues(e, fn) =
e match {
case is Array -> e map applyToValues($, fn)
case is Object -> e mapObject {($$): applyToValues($, fn)}
else -> fn(e) // transform value
}
----------------------------------------------------------------
fun applyToKeys(e, fn) =
e match {
case is Array -> e map applyToKeys($, fn)
case is Object -> e mapObject {(fn($$)): applyToKeys($, fn)}
else -> e // pass through values
}
Conclusion
Map and mapObject, combined with recursion and pattern matching on types, allows us to modify
ambiguously nested keys and values in an element
TODO
1. Can applyToValues and applyToKeys be modified so that the recursive call in the Object branch of
the match expression is in tail position?
2. Can we write a utility function that applies a function to values only when the key matches a
certain constraint?
Additional Info:
1. Full blog post on applyToValues - https://www.jerney.io/how-to-modify-all-values-of-an-element/
2. Full blog post on applyToValueWhenKey - https://www.jerney.io/dataweave-applywhenkey-
function/
3. Pattern Matching in DataWeave - https://docs.mulesoft.com/mule-runtime/4.1/dataweave-
pattern-matching
4. Pattern Matching regex - https://docs.mulesoft.com/mule-runtime/4.1/dataweave-pattern-
matching#pattern_match_regex
Questions?

More Related Content

What's hot

Demystifying the use of circuit breakers with MuleSoft
Demystifying the use of circuit breakers with MuleSoftDemystifying the use of circuit breakers with MuleSoft
Demystifying the use of circuit breakers with MuleSoftSandeep Deshmukh
 
Introduction to CloudHub 2.0
Introduction to CloudHub 2.0Introduction to CloudHub 2.0
Introduction to CloudHub 2.0NeerajKumar1965
 
MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)
MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)
MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)Prashanth Kurimella
 
MuleSoft Anypoint Platform and Three Tier Architecture
MuleSoft Anypoint  Platform and Three Tier ArchitectureMuleSoft Anypoint  Platform and Three Tier Architecture
MuleSoft Anypoint Platform and Three Tier ArchitectureHarish Kumar
 
Serverless integration with Knative and Apache Camel on Kubernetes
Serverless integration with Knative and Apache Camel on KubernetesServerless integration with Knative and Apache Camel on Kubernetes
Serverless integration with Knative and Apache Camel on KubernetesClaus Ibsen
 
Microservices on Anypoint Platform
Microservices on Anypoint PlatformMicroservices on Anypoint Platform
Microservices on Anypoint PlatformMuleSoft
 
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...Jitendra Bafna
 
Best Practices for API Security
Best Practices for API SecurityBest Practices for API Security
Best Practices for API SecurityMuleSoft
 
Mulesoft corporate template final
Mulesoft corporate template  final Mulesoft corporate template  final
Mulesoft corporate template final Bui Kiet
 
MuleSoft Runtime Fabric (RTF): Foundations : MuleSoft Virtual Muleys Meetups
MuleSoft Runtime Fabric (RTF): Foundations  : MuleSoft Virtual Muleys MeetupsMuleSoft Runtime Fabric (RTF): Foundations  : MuleSoft Virtual Muleys Meetups
MuleSoft Runtime Fabric (RTF): Foundations : MuleSoft Virtual Muleys MeetupsAngel Alberici
 
MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63
MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63
MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63Angel Alberici
 
Digital Transformation With MuleSoft : That Wins Customers
Digital Transformation With MuleSoft : That Wins CustomersDigital Transformation With MuleSoft : That Wins Customers
Digital Transformation With MuleSoft : That Wins Customerspqrs1234
 
Introduction to Selenium grid
Introduction to Selenium gridIntroduction to Selenium grid
Introduction to Selenium gridKnoldus Inc.
 
MuleSoft Online Meetup a Guide to RTF application deployment - October 2020
MuleSoft Online Meetup   a Guide to RTF application deployment  - October 2020MuleSoft Online Meetup   a Guide to RTF application deployment  - October 2020
MuleSoft Online Meetup a Guide to RTF application deployment - October 2020Royston Lobo
 
Object Store V2 Workshop
Object Store V2 WorkshopObject Store V2 Workshop
Object Store V2 WorkshopMuleSoft
 

What's hot (20)

Demystifying the use of circuit breakers with MuleSoft
Demystifying the use of circuit breakers with MuleSoftDemystifying the use of circuit breakers with MuleSoft
Demystifying the use of circuit breakers with MuleSoft
 
Introduction to CloudHub 2.0
Introduction to CloudHub 2.0Introduction to CloudHub 2.0
Introduction to CloudHub 2.0
 
MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)
MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)
MuleSoft Deployment Strategies (RTF vs Hybrid vs CloudHub)
 
MuleSoft Anypoint Platform and Three Tier Architecture
MuleSoft Anypoint  Platform and Three Tier ArchitectureMuleSoft Anypoint  Platform and Three Tier Architecture
MuleSoft Anypoint Platform and Three Tier Architecture
 
Serverless integration with Knative and Apache Camel on Kubernetes
Serverless integration with Knative and Apache Camel on KubernetesServerless integration with Knative and Apache Camel on Kubernetes
Serverless integration with Knative and Apache Camel on Kubernetes
 
Microservices on Anypoint Platform
Microservices on Anypoint PlatformMicroservices on Anypoint Platform
Microservices on Anypoint Platform
 
Introduction to MuleSoft
Introduction to MuleSoftIntroduction to MuleSoft
Introduction to MuleSoft
 
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
MuleSoft Surat Meetup#41 - Universal API Management, Anypoint Flex Gateway an...
 
Building APIs with Mule and Spring Boot
Building APIs with Mule and Spring BootBuilding APIs with Mule and Spring Boot
Building APIs with Mule and Spring Boot
 
Best Practices for API Security
Best Practices for API SecurityBest Practices for API Security
Best Practices for API Security
 
Mulesoft corporate template final
Mulesoft corporate template  final Mulesoft corporate template  final
Mulesoft corporate template final
 
DevOps & SRE at Google Scale
DevOps & SRE at Google ScaleDevOps & SRE at Google Scale
DevOps & SRE at Google Scale
 
MuleSoft Runtime Fabric (RTF): Foundations : MuleSoft Virtual Muleys Meetups
MuleSoft Runtime Fabric (RTF): Foundations  : MuleSoft Virtual Muleys MeetupsMuleSoft Runtime Fabric (RTF): Foundations  : MuleSoft Virtual Muleys Meetups
MuleSoft Runtime Fabric (RTF): Foundations : MuleSoft Virtual Muleys Meetups
 
MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63
MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63
MuleSoft Event Driven Architecture (EDA Patterns in MuleSoft) - VirtualMuleys63
 
Digital Transformation With MuleSoft : That Wins Customers
Digital Transformation With MuleSoft : That Wins CustomersDigital Transformation With MuleSoft : That Wins Customers
Digital Transformation With MuleSoft : That Wins Customers
 
Introduction to Selenium grid
Introduction to Selenium gridIntroduction to Selenium grid
Introduction to Selenium grid
 
Ansible - Hands on Training
Ansible - Hands on TrainingAnsible - Hands on Training
Ansible - Hands on Training
 
Tosca explained
Tosca explainedTosca explained
Tosca explained
 
MuleSoft Online Meetup a Guide to RTF application deployment - October 2020
MuleSoft Online Meetup   a Guide to RTF application deployment  - October 2020MuleSoft Online Meetup   a Guide to RTF application deployment  - October 2020
MuleSoft Online Meetup a Guide to RTF application deployment - October 2020
 
Object Store V2 Workshop
Object Store V2 WorkshopObject Store V2 Workshop
Object Store V2 Workshop
 

Similar to Data weave 2.0 advanced (recursion, pattern matching)

Data weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsData weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsManjuKumara GH
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsJoshua Erney
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameAntony Stubbs
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresqueBret McGuire
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1Prerna Sharma
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part維佋 唐
 
Ceylon idioms by Gavin King
Ceylon idioms by Gavin KingCeylon idioms by Gavin King
Ceylon idioms by Gavin KingUnFroMage
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlanDeepak Lakhlan
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3dplunkett
 
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and TensorfowAaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and TensorfowAminaRepo
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 

Similar to Data weave 2.0 advanced (recursion, pattern matching) (20)

Data weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsData weave 2.0 language fundamentals
Data weave 2.0 language fundamentals
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
DataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language FundamentalsDataWeave 2.0 Language Fundamentals
DataWeave 2.0 Language Fundamentals
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part
 
Ceylon idioms by Gavin King
Ceylon idioms by Gavin KingCeylon idioms by Gavin King
Ceylon idioms by Gavin King
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Core java
Core javaCore java
Core java
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlan
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and TensorfowAaa ped-23-Artificial Neural Network: Keras and Tensorfow
Aaa ped-23-Artificial Neural Network: Keras and Tensorfow
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
java_lect_03-2.ppt
java_lect_03-2.pptjava_lect_03-2.ppt
java_lect_03-2.ppt
 
Javascript
JavascriptJavascript
Javascript
 

More from ManjuKumara GH

Mulesoft Meetup Cryptography Module
Mulesoft Meetup Cryptography ModuleMulesoft Meetup Cryptography Module
Mulesoft Meetup Cryptography ModuleManjuKumara GH
 
AVRO to JSON Conversion
AVRO to JSON ConversionAVRO to JSON Conversion
AVRO to JSON ConversionManjuKumara GH
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupManjuKumara GH
 
Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8ManjuKumara GH
 
Baltimore july2021 final
Baltimore july2021 finalBaltimore july2021 final
Baltimore july2021 finalManjuKumara GH
 
How to Secure Mule API's With a Demo
How to Secure Mule API's With a DemoHow to Secure Mule API's With a Demo
How to Secure Mule API's With a DemoManjuKumara GH
 
Baltimore sep2019 mule_softsfdc
Baltimore sep2019 mule_softsfdcBaltimore sep2019 mule_softsfdc
Baltimore sep2019 mule_softsfdcManjuKumara GH
 
Mapfilterreducepresentation
MapfilterreducepresentationMapfilterreducepresentation
MapfilterreducepresentationManjuKumara GH
 
Baltimore nov2018 meetup
Baltimore nov2018 meetupBaltimore nov2018 meetup
Baltimore nov2018 meetupManjuKumara GH
 
Baltimore jan2019 mule4
Baltimore jan2019 mule4Baltimore jan2019 mule4
Baltimore jan2019 mule4ManjuKumara GH
 

More from ManjuKumara GH (10)

Mulesoft Meetup Cryptography Module
Mulesoft Meetup Cryptography ModuleMulesoft Meetup Cryptography Module
Mulesoft Meetup Cryptography Module
 
AVRO to JSON Conversion
AVRO to JSON ConversionAVRO to JSON Conversion
AVRO to JSON Conversion
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore Meetup
 
Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8
 
Baltimore july2021 final
Baltimore july2021 finalBaltimore july2021 final
Baltimore july2021 final
 
How to Secure Mule API's With a Demo
How to Secure Mule API's With a DemoHow to Secure Mule API's With a Demo
How to Secure Mule API's With a Demo
 
Baltimore sep2019 mule_softsfdc
Baltimore sep2019 mule_softsfdcBaltimore sep2019 mule_softsfdc
Baltimore sep2019 mule_softsfdc
 
Mapfilterreducepresentation
MapfilterreducepresentationMapfilterreducepresentation
Mapfilterreducepresentation
 
Baltimore nov2018 meetup
Baltimore nov2018 meetupBaltimore nov2018 meetup
Baltimore nov2018 meetup
 
Baltimore jan2019 mule4
Baltimore jan2019 mule4Baltimore jan2019 mule4
Baltimore jan2019 mule4
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Data weave 2.0 advanced (recursion, pattern matching)

  • 1. DataWeave 2.0 Advanced Concepts - Recursion & Pattern Matching Joshua Erney ● www.jerney.io (Blog) ● @jerney_io (Twitter) ● www.linkedin.com/in/jerney
  • 2. Agenda 1. Introduction 2. Quick review of basics 3. Looping / Recursion a. Tail Call Optimization 4. Pattern Matching a. By predicate expressions b. By data type 5. Combined Examples / Demos a. Use Case 1 - applyToValues b. Use Case 2 - applyToKeys 6. Questions
  • 3. Who Am I? Why Should You Listen To Me?! ● Programming since ‘11 (not bragging) ○ Java, Python, JavaScript ● Working w/ MuleSoft products for about 3 years ● Saw no DataWeave experts at my company or in the community at the time, I LOVE learning programming languages, so decided to focus efforts there ● Started learning DataWeave about the same time Functional Programming started making sense to me
  • 4. Disclaimer I don’t work for MuleSoft, and I’ve never seen the source code for DataWeave. Because of this, I have no way of knowing with 100% certainty how the language works; DataWeave is a black box to me. Opinions are my own and do not necessarily reflect those of my employer.
  • 5. A Quick Review of the Basics ● DataWeave is a domain-specific language created specifically to optimize data transformations regardless of source and target formats ● Fully-fledged programming language ● Adheres to the core tenets of functional programming, i.e., it is a functional programming language
  • 6. A Quick Review of the Basics (Cont.) ● Most transformations are done using `map`, `filter`, or `reduce` ○ `map` - transforms elements in an array ○ `filter` - removes elements in an array ○ `reduce` - general purpose tool for doing pretty much anything else with an array. Great for transforming arrays into objects or scalar values like strings and numbers. ● Data structures in DataWeave are immutable (this restriction is essentially the crux of this talk) ● If you want a deep dive into the basics (highly recommended), you should check out the webinar I did w/ Manik Magar: https://www.youtube.com/watch?v=r-jjcHPEP34
  • 8. Why is iteration part of “Advanced Dataweave”? ● Conceptually, it isn’t, we just don’t need to think about it that much ● DataWeave’s immutable data structures present a barrier to using the iteration techniques typically used in Java
  • 9. Iteration in Java (Imperative) for (i = 0; i < 100; i++) { System.out.println(i); } There are a couple of issues here that make this style of looping incompatible with DataWeave: 1. i++, this changes the variable i in place, meaning i is not immutable. 2. System.out.println(i);, we could put any number of statements with side- effects in the body of the loop. Other looping constructs like while have the same property.
  • 10. Iteration in DataWeave (Functional) ● We can iterate using one of two strategies: a. Reduce b. Recursion
  • 11. What is recursion? According to Wikipedia: Recursion in computer science is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem (as opposed to iteration). According to me, for this talk: Recursion is when a function calls itself for the purposes of looping in DataWeave.
  • 12. Recursion Example %dw 2.0 output application/json var range = 1 to 10 fun recurSum(arr, total=0) = if not isEmpty(arr) recurSum(arr[1 to -1], total + arr[0]) else total --- recurSum(range) // 1 + 2 + 3 + …, 10 = 45
  • 14. An Aside: Looping with Reduce Most of the times when you’re looping with recursion to get from an array to a single value, it’s better (and safer) to use `reduce`. Here’s the previous example using recursion instead: fun recurSum(arr) = arr reduce (n, total=0) -> total + n If you can use `reduce` instead of recursion, you should do so.
  • 15. A Problem with Recursion ● If you’re not careful, and/or your language does not support tail call optimization, you can run out of memory. This results in a stack overflow ● Tail call optimization is an optimization that the language implementation makes so that recursion is implemented as iteration, so that it doesn’t blow the stack ● Tail call optimization is supported in DataWeave since 2.0
  • 16. What is a tail call? ● A tail call is a call to a function that is performed as the final action needed in the function body.
  • 17. Tail call examples Tail Call (recurSum is the last call in the function body) fun recurSum(arr, total=0) = if not isEmpty(arr) recurSum(arr[1 to -1], total + arr[0]) else total Not a Tail Call (function still must add the result of recurSum to arr[0]) fun recurSum(arr) = if not isEmpty(arr) arr[0] + recurSum(arr[1 to -1]) else 0
  • 19. What is Pattern Matching? Most people think of pattern matching as a much more robust switch statement. It’s really important to know that `match` is not a statement, it is an expression, and therefore evaluates to a value. In DataWeave, we use the `match`, `case`, and `else` keywords to perform pattern matching, and it can perform much like a switch statement (but again, it returns): “Hello” match { case “Hello” -> “World!” case “Goodbye” -> “Space!” else -> “Where am I?” } // Returns “World!”
  • 20. What else can we match on? We’re not just limited to strings, we can match on 1. any literals (booleans, numbers, etc), 2. predicate expressions 3. type 4. regex (we won’t go over this, its use will be intuitive after going over the other matchables)
  • 21. Matching on Predicate Expressions ● A predicate expression is an expression that evaluates to true or false ● With `match`, this predicate expression usually takes the form `if <boolean test>` ● When using predicate expressions with `match`, `match` will match with the first predicate expression that evaluates to true, and ignore the rest ● With predicate expressions, you need to specify the name that the value to match will be referred to in the predicate expression (this is always an option, even though it was not shown in the previous example)
  • 22. Matching on Predicate Expressions (Cont.)
  • 23. Matching on Type We can also match on type: [1,2,3] match { case is Array -> “We have an array” case is Object -> “We have an object” else -> “We have neither an array or object” } // Returns “We have an array”
  • 24. Combining Pattern Matching and Recursion to Navigate Nested Data
  • 25. Use Case 1: We need a utility function that will modify all of the values in an element, regardless of how deeply they’re nested. An element in this case is either an Object, Array, or any combination of the two. How do we approach this?
  • 26. Use Case 1: Approach ● We want to write a function that can be reused among ANY use case that needs the same behavior ● The use case doesn’t specify what modification should take place, so our function should probably take another function as a parameter that describes this behavior, instead of hard-coding it ● We need to determine a way to navigate through a series of ambiguously nested elements, or potentially no nesting at all (e.g. 1-dimensional array)
  • 27. Use Case 1: Function Signature Ultimately, we’re going to want something like this: applyToValues( e: Object|Array, fn: (Scalar) -> Scalar ) -> Object|Array Please note that Scalar isn’t a DW type, I’m just using it to represent that what gets passed into fn and that what fn returns should be a single value, not a collection. Strings will classify as Scalar, not collection of chars.
  • 28. Use Case 1: Implementation fun applyToValues(e, fn) = e match { case is Array -> e map applyToValues($, fn) case is Object -> e mapObject {($$): applyToValues($, fn)} else -> fn(e) // transform value }
  • 29. Use Case 1: Notes While the Array branch of the `match` has the recursive call in tail position, the Object branch of the `match` does not. Be careful using this on very large elements.
  • 30. Use Case 2: We need a utility function that will modify all of the keys in an element, regardless of how deeply they’re nested. An element in this case is either an Object, Array, or any combination of the two. How do we approach this?
  • 31. Use Case 2: Approach ● We want to write a function that can be reused among ANY use case that needs the same behavior ● The use case doesn’t specify what modification should take place, so our function should probably take another function as a parameter that describes this behavior, instead of hard-coding it ● We need to determine a way to navigate through a series of ambiguously nested elements, or potentially no nesting at all (e.g. 1-dimensional array)
  • 32. Use Case 2: Function Signature Same as our previous function, but we’ll call it applyToKeys
  • 33. Use Case 2: Implementation fun applyToKeys(e, fn) = e match { case is Array -> e map applyToKeys($, fn) case is Object -> e mapObject {(fn($$)): applyToKeys($, fn)} else -> e // pass through values }
  • 35. Similarities fun applyToValues(e, fn) = e match { case is Array -> e map applyToValues($, fn) case is Object -> e mapObject {($$): applyToValues($, fn)} else -> fn(e) // transform value } ---------------------------------------------------------------- fun applyToKeys(e, fn) = e match { case is Array -> e map applyToKeys($, fn) case is Object -> e mapObject {(fn($$)): applyToKeys($, fn)} else -> e // pass through values }
  • 36. Conclusion Map and mapObject, combined with recursion and pattern matching on types, allows us to modify ambiguously nested keys and values in an element
  • 37. TODO 1. Can applyToValues and applyToKeys be modified so that the recursive call in the Object branch of the match expression is in tail position? 2. Can we write a utility function that applies a function to values only when the key matches a certain constraint?
  • 38. Additional Info: 1. Full blog post on applyToValues - https://www.jerney.io/how-to-modify-all-values-of-an-element/ 2. Full blog post on applyToValueWhenKey - https://www.jerney.io/dataweave-applywhenkey- function/ 3. Pattern Matching in DataWeave - https://docs.mulesoft.com/mule-runtime/4.1/dataweave- pattern-matching 4. Pattern Matching regex - https://docs.mulesoft.com/mule-runtime/4.1/dataweave-pattern- matching#pattern_match_regex

Editor's Notes

  1. More esoteric languages like Clojure, Racket, Scala, Ruby Saw no DataWeave experts: when I started using Mule dataweave was just coming out, people were skeptical to learn it because they were afraid it would get replaced again like Data Mapper did. After using it for a few months, I thought MuleSoft nailed it, didn’t see why it would ever be replaced. Dove in.
  2. Safer because we don’t have to worry about testing the input array for length, avoid stack overflows during development
  3. any literals (booleans, numbers), data types (we’ll use this heavily later), predicate expressions regex (we won’t go over this, its use will be intuitive after going over the other matchables)