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

Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...Eva Mave Ng
 
Mule access management - Managing Environments and Permissions
Mule access management - Managing Environments and PermissionsMule access management - Managing Environments and Permissions
Mule access management - Managing Environments and PermissionsShanky Gupta
 
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...Jitendra Bafna
 
Install Redis on Oracle Linux
Install Redis on Oracle LinuxInstall Redis on Oracle Linux
Install Redis on Oracle LinuxJohan Louwers
 
Power of Transformation with DataWeave 2.X Engine
Power of Transformation with DataWeave 2.X EnginePower of Transformation with DataWeave 2.X Engine
Power of Transformation with DataWeave 2.X EngineManish Kumar Yadav
 
MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용I Goo Lee
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeSimone Bordet
 
How To Install Sonar Qube Plugin In Anypoint Studio
How To Install Sonar Qube Plugin In Anypoint StudioHow To Install Sonar Qube Plugin In Anypoint Studio
How To Install Sonar Qube Plugin In Anypoint StudioSudha Ch
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
Pentesting GraphQL Applications
Pentesting GraphQL ApplicationsPentesting GraphQL Applications
Pentesting GraphQL ApplicationsNeelu Tripathy
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
 
Rtf v2 ingress muleSoft meetup self managed kubernetes
Rtf v2 ingress muleSoft meetup self managed kubernetesRtf v2 ingress muleSoft meetup self managed kubernetes
Rtf v2 ingress muleSoft meetup self managed kubernetesSandeep Deshmukh
 
Advanced messaging with Apache ActiveMQ
Advanced messaging with Apache ActiveMQAdvanced messaging with Apache ActiveMQ
Advanced messaging with Apache ActiveMQdejanb
 
Flow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECT
Flow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECTFlow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECT
Flow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECTSabrina Marechal
 
Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft
Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft
Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft Akshata Sawant
 

What's hot (20)

Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
Designing Apps for Runtime Fabric: Logging, Monitoring & Object Store Persist...
 
Mule access management - Managing Environments and Permissions
Mule access management - Managing Environments and PermissionsMule access management - Managing Environments and Permissions
Mule access management - Managing Environments and Permissions
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
MuleSoft Surat Meetup#52 - Flex Gateway (Port Based Routing V/S Path Based Ro...
 
Install Redis on Oracle Linux
Install Redis on Oracle LinuxInstall Redis on Oracle Linux
Install Redis on Oracle Linux
 
Power of Transformation with DataWeave 2.X Engine
Power of Transformation with DataWeave 2.X EnginePower of Transformation with DataWeave 2.X Engine
Power of Transformation with DataWeave 2.X Engine
 
MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
 
How To Install Sonar Qube Plugin In Anypoint Studio
How To Install Sonar Qube Plugin In Anypoint StudioHow To Install Sonar Qube Plugin In Anypoint Studio
How To Install Sonar Qube Plugin In Anypoint Studio
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
Selenium
SeleniumSelenium
Selenium
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Pentesting GraphQL Applications
Pentesting GraphQL ApplicationsPentesting GraphQL Applications
Pentesting GraphQL Applications
 
TestNG
TestNGTestNG
TestNG
 
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Rtf v2 ingress muleSoft meetup self managed kubernetes
Rtf v2 ingress muleSoft meetup self managed kubernetesRtf v2 ingress muleSoft meetup self managed kubernetes
Rtf v2 ingress muleSoft meetup self managed kubernetes
 
Advanced messaging with Apache ActiveMQ
Advanced messaging with Apache ActiveMQAdvanced messaging with Apache ActiveMQ
Advanced messaging with Apache ActiveMQ
 
Flow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECT
Flow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECTFlow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECT
Flow Tuning: Mule 3 vs. Mule 4 - MuleSoft Chicago CONNECT
 
Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft
Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft
Manchester MuleSoft Meetup #6 - Runtime Fabric with Mulesoft
 

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

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Recently uploaded (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

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)