SlideShare a Scribd company logo
1 of 17
Download to read offline
CopyrightPrismTech,2017
Angelo	Corsaro,	PhD
CTO,	ADLINK	Tech.	Inc.	
Co-Chair,	OMG	DDS-SIG	
angelo.corsaro@adlinktech.com
RUSTing
Partially Ordered
Rust Programming Ruminations
CopyrightPrismTech,2017
RUSTing is not a tutorial on the Rust programming
language.
I decided to create the RUSTing series as a way to
document and share programming idioms and techniques.
From time to time I’ll draw parallels with Haskell and Scala,
having some familiarity with one of them is useful but not
indispensable.
Prologue
CopyrightPrismTech,2017
Rust is a system programming
language that provides zero
cost high-level abstractions
and language-enforced
memory and concurrency
safety.
What is Rust?
CopyrightPrismTech,2017
Installing Rust is simple, just do*:
Getting Started
$ curl https://sh.rustup.rs -sSf | sh
I suggest you also install the documentation locally:
$ rustup component add rust-docs
Open the doc with:
$ rustup doc
CopyrightPrismTech,2017
Working with Monads…
CopyrightPrismTech,2017
The first monad one typically encounter is a List, but the
second one is usually the Maybe Monad
Like Scala, and differently from Haskell, Rust has named
the Monad used to model the “potential” presence of a
value as std::option::Option
Maybe is an Option
CopyrightPrismTech,2017
The Option Monad is an algebraic
data type with two variants,
Some(T) and None
The derive directives injects a
series of traits
The rest of the monad is
implemented in the impl clause
(see here)
The Option Monad
#[derive(Clone, Copy, PartialEq,
PartialOrd, Eq, Ord,
Debug, Hash)]
pub enum Option<T> {
None,
Some(T),
}
CopyrightPrismTech,2017
Depending on your background you may be familiar with at least
three ways of working with Option, and with Monad in generals
- map/flatMap
- map :: (a -> b) -> M a -> M b
- flatMap :: (a -> M b) -> M a -> M b
- Pattern Matching
- do construct in Haskell / for construct in Scala
Let’s investigate what the equivalents are in Rust
Working with an Option
CopyrightPrismTech,2017
Hardcore functional programmers live out of
map and flatMap
Rust’s Option type is equipped with a map
defined as:
In Rust’s , flatMap called and_then, is defined as:
The Orthodox Option
fn and_then<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> Option<U>
fn map<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> U
CopyrightPrismTech,2017
As a result the orthodox way of dealing with
options is to use map and and_then:
The Orthodox Option
let a = Some(18);
let b = Some(24);
let c = a.and_then(|x| {
b.map(|y| { x + y })
});
println!("{:?} + {:?} = {:?}", a, b, c);
[rust]: Some(18) + Some(24) = Some(42)
CopyrightPrismTech,2017
Another way to work with the Option type is
to use pattern matching as shown below:
Pattern Matching Option
let a = Some(18);
let b = Some(24);
let c = match a {
Some(x) => match b {
Some(y) => Some(x+y),
None => None
},
None => None
};
println!("{:?} + {:?} = {:?}", a, b, c);
[rust]: Some(18) + Some(24) = Some(42)
CopyrightPrismTech,2017
That was easy. Let’s try with strings…
Ownership and Moves
let s = Some(String::from(“Welcome to"));
let t = Some(String::from("Rust!"));
let u = s.and_then(|a| {
t.map(|b| { format!("{} {}", a, b).to_string()})
});
println!("{:?} + {:?} = {:?}", s, t, u);
[…]
error[E0382]: use of moved value: `s`
error[E0382]: use of moved value: `t`
CopyrightPrismTech,2017
The reason why the apparently innocent example does not
compile has to do with Rust Ownership and Move semantics.
Ownership and Moves
let s = Some(String::from(“Welcome to"));
let t = Some(String::from("Rust!"));
let u = s.and_then(|a| {
t.map(|b| { format!("{} {}", a, b).to_string()})
});
println!("{:?} + {:?} = {:?}", s, t, u);
The moved t is freed here
The moved s is freed here
CopyrightPrismTech,2017
To avoid moving the value held by the option into the
lambda we have to use as_ref
Ownership and Moves
let s = Some(String::from(“Welcome to"));
let t = Some(String::from("Rust!"));
let u = s.as_ref().and_then(|a| {
t.as_ref().map(|b| { format!("{} {}", a, b).to_string()})
});
println!("{:?} + {:?} = {:?}", s, t, u);
[…]
[rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")
CopyrightPrismTech,2017
You have to watch out for moves also when using pattern
matching. As a consequence the following snippet also
suffers from “unintended” move
Move & Pattern Matching
let s = Some(String::from(“Welcome to"));
let t = Some(String::from(“Rust!"));
let u = match s {
Some(a) => match t {
Some(b) => Some(format!("{} {}", a, b)),
None => None
},
None => None
};
println!("{:?} + {:?} = {:?}", s, t, u);
The moved s is freed here
The moved t is freed here
CopyrightPrismTech,2017
As we’ve seen with and_then/map the trick is to use
references. Please notice that as Option implements the
Copy trait we need to use the reference only on its
content — otherwise we would have had to match by &
Move & Pattern Matching
let s = Some(String::from(“Welcome to"));
let t = Some(String::from(“Rust!"));
let u = match s {
Some(ref a) => match t {
Some(ref b) => Some(format!("{} {}", a, b)),
None => None
},
None => None
};
println!("{:?} + {:?} = {:?}", s, t, u);
CopyrightPrismTech,2017
If you are fond of Haskell’s do or Scala’s for construct
you can achieve a similar syntactical sugar by using
Rust’s iterators
Iterating an Option
let s = Some(String::from(“Welcome to"));
let t = Some(String::from(“Rust!"));
let mut u = None;
for a in s.iter() {
for b in t.iter() {
u = Some(format!("{} {}", a, b))
}
}
println!("{:?} + {:?} = {:?}", s, t, u);
This is not my favourite way
as I don’t like to use
mutability so casually.
It’d be much nicer if the
for-loop would allow to
return a value
[…]
[rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")

More Related Content

Viewers also liked

Getting Started with Vortex
Getting Started with VortexGetting Started with Vortex
Getting Started with VortexAngelo Corsaro
 
Vortex II -- The Industrial IoT Connectivity Standard
Vortex II -- The  Industrial IoT  Connectivity StandardVortex II -- The  Industrial IoT  Connectivity Standard
Vortex II -- The Industrial IoT Connectivity StandardAngelo Corsaro
 
The Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
The Inside Story: How OPC UA and DDS Can Work Together in Industrial SystemsThe Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
The Inside Story: How OPC UA and DDS Can Work Together in Industrial SystemsReal-Time Innovations (RTI)
 
The Cloudy, Foggy and Misty Internet of Things -- Toward Fluid IoT Architect...
The Cloudy, Foggy and Misty Internet of Things --  Toward Fluid IoT Architect...The Cloudy, Foggy and Misty Internet of Things --  Toward Fluid IoT Architect...
The Cloudy, Foggy and Misty Internet of Things -- Toward Fluid IoT Architect...Angelo Corsaro
 
Data Sharing in Extremely Resource Constrained Envionrments
Data Sharing in Extremely Resource Constrained EnvionrmentsData Sharing in Extremely Resource Constrained Envionrments
Data Sharing in Extremely Resource Constrained EnvionrmentsAngelo Corsaro
 

Viewers also liked (6)

Getting Started with Vortex
Getting Started with VortexGetting Started with Vortex
Getting Started with Vortex
 
Vortex II -- The Industrial IoT Connectivity Standard
Vortex II -- The  Industrial IoT  Connectivity StandardVortex II -- The  Industrial IoT  Connectivity Standard
Vortex II -- The Industrial IoT Connectivity Standard
 
The Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
The Inside Story: How OPC UA and DDS Can Work Together in Industrial SystemsThe Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
The Inside Story: How OPC UA and DDS Can Work Together in Industrial Systems
 
Fog Computing Defined
Fog Computing DefinedFog Computing Defined
Fog Computing Defined
 
The Cloudy, Foggy and Misty Internet of Things -- Toward Fluid IoT Architect...
The Cloudy, Foggy and Misty Internet of Things --  Toward Fluid IoT Architect...The Cloudy, Foggy and Misty Internet of Things --  Toward Fluid IoT Architect...
The Cloudy, Foggy and Misty Internet of Things -- Toward Fluid IoT Architect...
 
Data Sharing in Extremely Resource Constrained Envionrments
Data Sharing in Extremely Resource Constrained EnvionrmentsData Sharing in Extremely Resource Constrained Envionrments
Data Sharing in Extremely Resource Constrained Envionrments
 

Similar to RUSTing -- Partially Ordered Rust Programming Ruminations

Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePeter Solymos
 
Presentation on use of r statistics
Presentation on use of r statisticsPresentation on use of r statistics
Presentation on use of r statisticsKrishna Dhakal
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Languagevsssuresh
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийSigma Software
 
Go generics. what is this fuzz about?
Go generics. what is this fuzz about?Go generics. what is this fuzz about?
Go generics. what is this fuzz about?Gabriel Habryn
 
2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumertirlukachaitanya
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programmingNimrita Koul
 
Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Samir Bessalah
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg MürkPlanet OS
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Write LESS. DO more.
Write LESS. DO more.Write LESS. DO more.
Write LESS. DO more.Eugene Nor
 
Mapreduce in Search
Mapreduce in SearchMapreduce in Search
Mapreduce in SearchAmund Tveit
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a MomentSergio Gil
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programmingAlberto Labarga
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)Christopher Roach
 

Similar to RUSTing -- Partially Ordered Rust Programming Ruminations (20)

Poetry with R -- Dissecting the code
Poetry with R -- Dissecting the codePoetry with R -- Dissecting the code
Poetry with R -- Dissecting the code
 
Presentation on use of r statistics
Presentation on use of r statisticsPresentation on use of r statistics
Presentation on use of r statistics
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Async and Parallel F#
Async and Parallel F#Async and Parallel F#
Async and Parallel F#
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола Мозговий
 
Go generics. what is this fuzz about?
Go generics. what is this fuzz about?Go generics. what is this fuzz about?
Go generics. what is this fuzz about?
 
2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer2015-10-23_wim_davis_r_slides.pptx on consumer
2015-10-23_wim_davis_r_slides.pptx on consumer
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013Big Data Analytics with Scala at SCALA.IO 2013
Big Data Analytics with Scala at SCALA.IO 2013
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg Mürk
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Write LESS. DO more.
Write LESS. DO more.Write LESS. DO more.
Write LESS. DO more.
 
Mapreduce in Search
Mapreduce in SearchMapreduce in Search
Mapreduce in Search
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)
 
go.ppt
go.pptgo.ppt
go.ppt
 

More from Angelo Corsaro

zenoh: The Edge Data Fabric
zenoh: The Edge Data Fabriczenoh: The Edge Data Fabric
zenoh: The Edge Data FabricAngelo Corsaro
 
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
Data Decentralisation: Efficiency, Privacy and Fair MonetisationData Decentralisation: Efficiency, Privacy and Fair Monetisation
Data Decentralisation: Efficiency, Privacy and Fair MonetisationAngelo Corsaro
 
zenoh: zero overhead pub/sub store/query compute
zenoh: zero overhead pub/sub store/query computezenoh: zero overhead pub/sub store/query compute
zenoh: zero overhead pub/sub store/query computeAngelo Corsaro
 
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolzenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolAngelo Corsaro
 
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolzenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolAngelo Corsaro
 
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Breaking the Edge -- A Journey Through Cloud, Edge and Fog ComputingBreaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Breaking the Edge -- A Journey Through Cloud, Edge and Fog ComputingAngelo Corsaro
 
fog05: The Fog Computing Infrastructure
fog05: The Fog Computing Infrastructurefog05: The Fog Computing Infrastructure
fog05: The Fog Computing InfrastructureAngelo Corsaro
 
Cyclone DDS: Sharing Data in the IoT Age
Cyclone DDS: Sharing Data in the IoT AgeCyclone DDS: Sharing Data in the IoT Age
Cyclone DDS: Sharing Data in the IoT AgeAngelo Corsaro
 
fog05: The Fog Computing Platform
fog05: The Fog Computing Platformfog05: The Fog Computing Platform
fog05: The Fog Computing PlatformAngelo Corsaro
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture FourAngelo Corsaro
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture ThreeAngelo Corsaro
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture OneAngelo Corsaro
 
The DDS Security Standard
The DDS Security StandardThe DDS Security Standard
The DDS Security StandardAngelo Corsaro
 
The Data Distribution Service
The Data Distribution ServiceThe Data Distribution Service
The Data Distribution ServiceAngelo Corsaro
 
DDS in Action -- Part I
DDS in Action -- Part IDDS in Action -- Part I
DDS in Action -- Part IAngelo Corsaro
 

More from Angelo Corsaro (20)

Zenoh: The Genesis
Zenoh: The GenesisZenoh: The Genesis
Zenoh: The Genesis
 
zenoh: The Edge Data Fabric
zenoh: The Edge Data Fabriczenoh: The Edge Data Fabric
zenoh: The Edge Data Fabric
 
Zenoh Tutorial
Zenoh TutorialZenoh Tutorial
Zenoh Tutorial
 
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
Data Decentralisation: Efficiency, Privacy and Fair MonetisationData Decentralisation: Efficiency, Privacy and Fair Monetisation
Data Decentralisation: Efficiency, Privacy and Fair Monetisation
 
zenoh: zero overhead pub/sub store/query compute
zenoh: zero overhead pub/sub store/query computezenoh: zero overhead pub/sub store/query compute
zenoh: zero overhead pub/sub store/query compute
 
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolzenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocol
 
zenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocolzenoh -- the ZEro Network OverHead protocol
zenoh -- the ZEro Network OverHead protocol
 
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Breaking the Edge -- A Journey Through Cloud, Edge and Fog ComputingBreaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
Breaking the Edge -- A Journey Through Cloud, Edge and Fog Computing
 
Eastern Sicily
Eastern SicilyEastern Sicily
Eastern Sicily
 
fog05: The Fog Computing Infrastructure
fog05: The Fog Computing Infrastructurefog05: The Fog Computing Infrastructure
fog05: The Fog Computing Infrastructure
 
Cyclone DDS: Sharing Data in the IoT Age
Cyclone DDS: Sharing Data in the IoT AgeCyclone DDS: Sharing Data in the IoT Age
Cyclone DDS: Sharing Data in the IoT Age
 
fog05: The Fog Computing Platform
fog05: The Fog Computing Platformfog05: The Fog Computing Platform
fog05: The Fog Computing Platform
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture One
 
The DDS Security Standard
The DDS Security StandardThe DDS Security Standard
The DDS Security Standard
 
The Data Distribution Service
The Data Distribution ServiceThe Data Distribution Service
The Data Distribution Service
 
DDS In Action Part II
DDS In Action Part IIDDS In Action Part II
DDS In Action Part II
 
DDS in Action -- Part I
DDS in Action -- Part IDDS in Action -- Part I
DDS in Action -- Part I
 

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

RUSTing -- Partially Ordered Rust Programming Ruminations

  • 2. CopyrightPrismTech,2017 RUSTing is not a tutorial on the Rust programming language. I decided to create the RUSTing series as a way to document and share programming idioms and techniques. From time to time I’ll draw parallels with Haskell and Scala, having some familiarity with one of them is useful but not indispensable. Prologue
  • 3. CopyrightPrismTech,2017 Rust is a system programming language that provides zero cost high-level abstractions and language-enforced memory and concurrency safety. What is Rust?
  • 4. CopyrightPrismTech,2017 Installing Rust is simple, just do*: Getting Started $ curl https://sh.rustup.rs -sSf | sh I suggest you also install the documentation locally: $ rustup component add rust-docs Open the doc with: $ rustup doc
  • 6. CopyrightPrismTech,2017 The first monad one typically encounter is a List, but the second one is usually the Maybe Monad Like Scala, and differently from Haskell, Rust has named the Monad used to model the “potential” presence of a value as std::option::Option Maybe is an Option
  • 7. CopyrightPrismTech,2017 The Option Monad is an algebraic data type with two variants, Some(T) and None The derive directives injects a series of traits The rest of the monad is implemented in the impl clause (see here) The Option Monad #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Option<T> { None, Some(T), }
  • 8. CopyrightPrismTech,2017 Depending on your background you may be familiar with at least three ways of working with Option, and with Monad in generals - map/flatMap - map :: (a -> b) -> M a -> M b - flatMap :: (a -> M b) -> M a -> M b - Pattern Matching - do construct in Haskell / for construct in Scala Let’s investigate what the equivalents are in Rust Working with an Option
  • 9. CopyrightPrismTech,2017 Hardcore functional programmers live out of map and flatMap Rust’s Option type is equipped with a map defined as: In Rust’s , flatMap called and_then, is defined as: The Orthodox Option fn and_then<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> Option<U> fn map<U, F>(self, f: F) -> Option<U> where F: FnOnce(T) -> U
  • 10. CopyrightPrismTech,2017 As a result the orthodox way of dealing with options is to use map and and_then: The Orthodox Option let a = Some(18); let b = Some(24); let c = a.and_then(|x| { b.map(|y| { x + y }) }); println!("{:?} + {:?} = {:?}", a, b, c); [rust]: Some(18) + Some(24) = Some(42)
  • 11. CopyrightPrismTech,2017 Another way to work with the Option type is to use pattern matching as shown below: Pattern Matching Option let a = Some(18); let b = Some(24); let c = match a { Some(x) => match b { Some(y) => Some(x+y), None => None }, None => None }; println!("{:?} + {:?} = {:?}", a, b, c); [rust]: Some(18) + Some(24) = Some(42)
  • 12. CopyrightPrismTech,2017 That was easy. Let’s try with strings… Ownership and Moves let s = Some(String::from(“Welcome to")); let t = Some(String::from("Rust!")); let u = s.and_then(|a| { t.map(|b| { format!("{} {}", a, b).to_string()}) }); println!("{:?} + {:?} = {:?}", s, t, u); […] error[E0382]: use of moved value: `s` error[E0382]: use of moved value: `t`
  • 13. CopyrightPrismTech,2017 The reason why the apparently innocent example does not compile has to do with Rust Ownership and Move semantics. Ownership and Moves let s = Some(String::from(“Welcome to")); let t = Some(String::from("Rust!")); let u = s.and_then(|a| { t.map(|b| { format!("{} {}", a, b).to_string()}) }); println!("{:?} + {:?} = {:?}", s, t, u); The moved t is freed here The moved s is freed here
  • 14. CopyrightPrismTech,2017 To avoid moving the value held by the option into the lambda we have to use as_ref Ownership and Moves let s = Some(String::from(“Welcome to")); let t = Some(String::from("Rust!")); let u = s.as_ref().and_then(|a| { t.as_ref().map(|b| { format!("{} {}", a, b).to_string()}) }); println!("{:?} + {:?} = {:?}", s, t, u); […] [rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")
  • 15. CopyrightPrismTech,2017 You have to watch out for moves also when using pattern matching. As a consequence the following snippet also suffers from “unintended” move Move & Pattern Matching let s = Some(String::from(“Welcome to")); let t = Some(String::from(“Rust!")); let u = match s { Some(a) => match t { Some(b) => Some(format!("{} {}", a, b)), None => None }, None => None }; println!("{:?} + {:?} = {:?}", s, t, u); The moved s is freed here The moved t is freed here
  • 16. CopyrightPrismTech,2017 As we’ve seen with and_then/map the trick is to use references. Please notice that as Option implements the Copy trait we need to use the reference only on its content — otherwise we would have had to match by & Move & Pattern Matching let s = Some(String::from(“Welcome to")); let t = Some(String::from(“Rust!")); let u = match s { Some(ref a) => match t { Some(ref b) => Some(format!("{} {}", a, b)), None => None }, None => None }; println!("{:?} + {:?} = {:?}", s, t, u);
  • 17. CopyrightPrismTech,2017 If you are fond of Haskell’s do or Scala’s for construct you can achieve a similar syntactical sugar by using Rust’s iterators Iterating an Option let s = Some(String::from(“Welcome to")); let t = Some(String::from(“Rust!")); let mut u = None; for a in s.iter() { for b in t.iter() { u = Some(format!("{} {}", a, b)) } } println!("{:?} + {:?} = {:?}", s, t, u); This is not my favourite way as I don’t like to use mutability so casually. It’d be much nicer if the for-loop would allow to return a value […] [rust]: Some(“Welcome to") + Some("Rust!") = Some("Welcome to Rust!")