SlideShare a Scribd company logo
HEY!There’s OCaml In My Rust!
Kel Cecil
@praisechaos
I ❤ Languages
Incredible
Shrinking
Operating System
Steve Jones
DevOps Days 2015
OCaml is pretty cool!
It's a functional programming language...
# let double x = x * 2 in
List.map double [ 1; 2; 3 ];;
- : int list = [2; 4; 6]
• OCaml is an almost pure functional programming
language by default.
• Functions are first-class citizens.
... and an imperative programming language...
let update_collectable_value order new_value =
order.old_value <- order.current_value;
order.current_value <- new_value;
order
• It can be convenient to be able to code in the
imperative style.
• OCaml includes imperative constructs like for and
while loops.
... and an object-oriented language!
class ['a] queue init = object
val mutable q: 'a list = init
method enqueue item =
q <- q @ item
end;;
• OCaml can also be object-oriented if needed.
OCaml powers some pretty sweet stuff.
• MirageOS: Unikernel tech recently acquired by
Docker
• Flow: A static type checker for JavaScript
• Hack: A programming languages for Facebook's
HHVM
• and...
Rust's first compiler!
• rustboot was written in OCaml
• Replaced for Rust 0.7
Rust is pretty excellent too!
• Guaranteed Memory Safety
• Threads without data races
• Incredibly fast
• Crazy awesome potential
Rust was inspired by OCaml
in a few interesting ways!
Let's start with a simple, imperative OCaml program
• Define a type named collectable_value that olds the
previous value and current value of an item.
• Provide a function to update the current value and
update the old value.
• Have a "main" function to create the record and
update the value.
Starting with our type
type collectable_value = {
mutable old_value: float;
mutable current_value: float;
}
• A record is a collection of values stored together as a
data type.
• Values are immutable by default but can be marked
as mutable.
Adding our first function
let update_collectable_value collectable new_value =
collectable.old_value <- collectable.current_value;
collectable.current_value <- new_value;
collectable
• Define a function with a let-binding.
• Accepts a collectablevalue record (collectable) and a
float (newvalue).
• Updates and returns the record.
Adding a "main"
let _ =
let pinball_machine = {
old_value = 0.0;
current_value = 800.00;
} in
update_collectable_value pinball_machine 900.0
• Underscore discards the return value.
• This let-binding allows us to execute code at the top
level.
Anything seem a little Rust-y
to you?
type collectable_value = {
mutable old_value: float;
mutable current_value: float;
}
let update_collectable_value order new_value =
order.old_value <- order.current_value;
order.current_value <- new_value;
order
let _ =
let pinball_machine = {
old_value = 0.0;
current_value = 800.00;
} in
update_collectable_value pinball_machine 900.0
Semicolon Separation in OCaml
let update_collectable_value collectable new_value =
collectable.old_value <- collectable.current_value;
collectable.current_value <- new_value;
collectable
• Notice the semi-colons separating the expressions?
• The last expression is the return value for the
function.
• Look familiar?
Statements in Rust
fn greeting() -> String {
let greeting = "Hello, there!";
String::from(greeting) // Return value from fn
}
• Rust code is mostly statements.
• Most common statements are
• declaring a variable
• using an expression with a semi-colon
• Last expression omitting the semi-colon is returned.
What is Type
Inference?
• Automatic deduction of the data type of an
expression.
Rust's Type Inference
// Rust knows that name is a String.
let name = "Kel!"
• Rust's type inference is loosely based on the
Hindley-Milner algorithm4
.
• Extensions were added to use accommodate
subtyping.
4
https://github.com/rust-lang/rust/blob/master/src/librustc/infer/README.md
OCaml's Type Inference
(* OCaml also knows this is a string. *)
let name = "Kel!"
• ML originally used the Hindley-Milner algorithm.
• OCaml's implementation works through solving
constraints.
• Tons of research hours poured into their
algorithm(s)5
5
https://www.cis.upenn.edu/~sweirich/icfp-plmw15/slides/pottier.pdf
Workshop: Binary Search Tree
• Follow along in your IDEs!
• Learn about binary search trees here:
• https://en.wikipedia.org/wiki/Binary_search_tree
• Check out the examples
• https://github.com/kelcecil/rust-ocaml-workshop
Building our Tree Structure
OCaml, then Rust.
Tree in OCaml
type tree;;
• Types in OCaml are defined with the type keyword.
Tree in OCaml
type tree =
Empty
;;
• We need to represent a node that does not exist.
• We'll represent this as Empty.
Tree in OCaml
type tree =
| Empty
| Node
;;
• We also want to represent a node that exists.
• We'll represent this as node.
Tree in OCaml
type 'a tree =
| Empty
| Node of 'a * 'a tree * 'a tree
;;
• Our node must have a key, a left child, and a right
child.
• Node now contains generic 'a that is our key.
• We also have two values of tree presenting our left
and right leaves.
Algebraic Data Types
• Composite type formed from other types
• Common types of Algebraic Types
• Product Types
• Sum Types
Product Types
• Compound types in a structure
• Operands of the product are types
• Structure is determined by fixed order of operands
(* Record *)
type person = {name: string; age: int};;
let kel = {name = "Kel"; age = 30};;
(* Tuple *)
let next_obsession = ("Dead Rising 4", 59.99);;
Tuples and records are product types in OCaml
let my_love = ("Rust", 9001)
• Tuples are product types in Rust
• There's also the unit () type
• Tuple with no operands.
Sum Types
type 'a tree =
| Empty
| Node of 'a * 'a tree * 'a tree
;;
• Multiple classes of values called variants.
• Each class has it's own constructor.
• Class represents it's own concept
Tree in Rust
enum Tree {
Empty
}
• Algebraic data types are enums in Rust.
• We start with defining Empty.
enum Tree<T>{
Empty,
Node(T, Box<Tree<T>>, Box<Tree<T>>)
}
• Node is a generic variable for the key, a left leaf, and
a right leaf.
• Recursive structures must be boxed1
.
• We want the size of the Tree to be bounded.
• Pointer using Box allocates memory on the heap.
1
https://doc.rust-lang.org/std/boxed/
Recap: Rust and OCaml Tree Structures6
type 'a tree =
| Empty
| Node of 'a * 'a tree * 'a tree
;;
enum Tree<T>{
Empty,
Node(T, Box<Tree<T>>, Box<Tree<T>>)
}
6
https://github.com/kelcecil/rust-ocaml-workshop/tree/master/workshop/01-structure
Writing a depth function
depth (OCaml using Pattern Matching)
let rec depth tree =
match tree with
| Empty -> 0
| Node(_, left, right) -> 1 + max (depth left) (depth right)
;;
• let defines a variable or function in OCaml.
• rec denotes a recursive function.
• The match keyword matches by data type.
depth (OCaml using function)
let rec depth = function
| Empty -> 0
| Node(_, left, right) -> 1 + max (depth left) (depth right)
;;
• OCaml functions can also be defined using the
function keyword.
• function has built in pattern matching for types.
• This syntax is a bit more concise.
Unit Test for depth (OCaml)
open OUnit
(* tree type here *)
(* depth function here *)
let test_tree = Node(5, Node(3, Empty, Empty), Empty)
let tree_depth _ =
assert_equal 2 (depth test_tree)
let suite = "Binary Tree Tests" >::: ["tree_depth" >:: tree_depth]
let _ =
run_test_tt_main suite
Running OCaml Tests
ocamlfind ocamlc -package oUnit -linkpkg -o <output_binary> <source_file>
depth (Rust)
impl<T> Tree<T>
where T: PartialOrd
{
fn depth(&self) -> usize {
match *self {
Tree::Empty => 0,
Tree::Node(_, ref left, ref right) =>
1 + max(left.depth(), right.depth())
}
}
}
• Restricting our generic to PartialOrd lets us choose
our key type similarly to OCaml.
Unit Test for depth (Rust)
#[test]
fn depth_test() {
let tree = Tree::Node(5, Box::new(
Tree::Node(4,Box::new(Tree::Empty),
Box::new(Tree::Empty)
)),
Box::new(Tree::Empty));
assert!(tree.depth() == 2)
}
Running Rust Unit Tests
rustc --test <source_file>
tl;dr
• OCaml's inspiration for Rust can been seen in:
• Semicolon Statement Separation
• Type Inference
• Algebraic Data Types
• Pattern Matching
• Rust and OCaml are both totally awesome.
Time for you to try!
• Adjust the our tree implementations to hold values.
• Write insert functions for OCaml and Rust!
• Write member functions for OCaml and Rust!
Stumped? No problem.
• https://github.com/kelcecil/rust-ocaml-workshop
• Clone the repository and experiment!
• Check out the other random examples in the
repository.
• Ask for help!
Branching in OCaml
OCaml has an if statement like so2
:
if <boolean_condition> then
<expression>
else if <boolean_condition> then
<expression>
else <expression>
2
https://ocaml.org/learn/tutorials/ifstatementsloopsandrecursion.html

More Related Content

What's hot

Algorithmique
AlgorithmiqueAlgorithmique
Algorithmique
Zakariyaa AIT ELMOUDEN
 
Chapitre iii interruptions
Chapitre iii interruptionsChapitre iii interruptions
Chapitre iii interruptions
Sana Aroussi
 
Active directory
Active directoryActive directory
Active directory
kamar MEDDAH
 
Ch2_ la récursivité.pdf
Ch2_ la récursivité.pdfCh2_ la récursivité.pdf
Ch2_ la récursivité.pdf
FadouaBouafifSamoud
 
Equipements d'interconnexion
Equipements d'interconnexionEquipements d'interconnexion
Equipements d'interconnexion
Ines Kechiche
 
InputMethodKit超入門
InputMethodKit超入門InputMethodKit超入門
InputMethodKit超入門
Wataru Kimura
 
Algorithmes d'approximation
Algorithmes d'approximationAlgorithmes d'approximation
Algorithmes d'approximation
mohamed_SAYARI
 
(équipements réseau)
(équipements réseau)(équipements réseau)
(équipements réseau)
Anouar Abtoy
 
Travaux Dirigée: Notions de bases dans les réseaux
Travaux Dirigée: Notions de bases dans les réseauxTravaux Dirigée: Notions de bases dans les réseaux
Travaux Dirigée: Notions de bases dans les réseaux
Ines Kechiche
 
Correction TD Adressage IP.pdf
Correction  TD Adressage IP.pdfCorrection  TD Adressage IP.pdf
Correction TD Adressage IP.pdf
ssuser18776b
 
Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019
Aziz Darouichi
 
Spanning-Tree
Spanning-TreeSpanning-Tree
Spanning-Tree
Thomas Moegli
 
Analyse de l’activité enseignante Extrait texte de Pierre Pastre
Analyse de l’activité enseignante Extrait texte de Pierre Pastre Analyse de l’activité enseignante Extrait texte de Pierre Pastre
Analyse de l’activité enseignante Extrait texte de Pierre Pastre
philip61
 
Introduction_Reseau.ppt
Introduction_Reseau.pptIntroduction_Reseau.ppt
Introduction_Reseau.ppt
AmalHadri2
 
TD_complet_reseau__CISCO__Packet Tracer.pdf
TD_complet_reseau__CISCO__Packet Tracer.pdfTD_complet_reseau__CISCO__Packet Tracer.pdf
TD_complet_reseau__CISCO__Packet Tracer.pdf
Ines Ben Hassine
 
Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...
Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...
Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...
ENSET, Université Hassan II Casablanca
 
Chapitre 6 hachage statique
Chapitre 6 hachage statiqueChapitre 6 hachage statique
Chapitre 6 hachage statique
Sana Aroussi
 

What's hot (20)

Algorithmique
AlgorithmiqueAlgorithmique
Algorithmique
 
Chapitre iii interruptions
Chapitre iii interruptionsChapitre iii interruptions
Chapitre iii interruptions
 
Active directory
Active directoryActive directory
Active directory
 
Ch2_ la récursivité.pdf
Ch2_ la récursivité.pdfCh2_ la récursivité.pdf
Ch2_ la récursivité.pdf
 
Equipements d'interconnexion
Equipements d'interconnexionEquipements d'interconnexion
Equipements d'interconnexion
 
InputMethodKit超入門
InputMethodKit超入門InputMethodKit超入門
InputMethodKit超入門
 
Algorithmes d'approximation
Algorithmes d'approximationAlgorithmes d'approximation
Algorithmes d'approximation
 
Vpn
VpnVpn
Vpn
 
(équipements réseau)
(équipements réseau)(équipements réseau)
(équipements réseau)
 
Travaux Dirigée: Notions de bases dans les réseaux
Travaux Dirigée: Notions de bases dans les réseauxTravaux Dirigée: Notions de bases dans les réseaux
Travaux Dirigée: Notions de bases dans les réseaux
 
Correction TD Adressage IP.pdf
Correction  TD Adressage IP.pdfCorrection  TD Adressage IP.pdf
Correction TD Adressage IP.pdf
 
Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019Chapitre2fonctionscppv2019
Chapitre2fonctionscppv2019
 
Spanning-Tree
Spanning-TreeSpanning-Tree
Spanning-Tree
 
Analyse de l’activité enseignante Extrait texte de Pierre Pastre
Analyse de l’activité enseignante Extrait texte de Pierre Pastre Analyse de l’activité enseignante Extrait texte de Pierre Pastre
Analyse de l’activité enseignante Extrait texte de Pierre Pastre
 
Introduction_Reseau.ppt
Introduction_Reseau.pptIntroduction_Reseau.ppt
Introduction_Reseau.ppt
 
Résumé vlsm et cidr
Résumé vlsm et cidrRésumé vlsm et cidr
Résumé vlsm et cidr
 
TD_complet_reseau__CISCO__Packet Tracer.pdf
TD_complet_reseau__CISCO__Packet Tracer.pdfTD_complet_reseau__CISCO__Packet Tracer.pdf
TD_complet_reseau__CISCO__Packet Tracer.pdf
 
Récursivité
RécursivitéRécursivité
Récursivité
 
Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...
Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...
Mise en oeuvre des Frameworks de Machines et Deep Learning pour les Applicati...
 
Chapitre 6 hachage statique
Chapitre 6 hachage statiqueChapitre 6 hachage statique
Chapitre 6 hachage statique
 

Viewers also liked

Rust Synchronization Primitives
Rust Synchronization PrimitivesRust Synchronization Primitives
Rust Synchronization Primitives
Corey Richardson
 
Performance Comparison of Mutex, RWLock and Atomic types in Rust
Performance Comparison of Mutex, RWLock and  Atomic types in RustPerformance Comparison of Mutex, RWLock and  Atomic types in Rust
Performance Comparison of Mutex, RWLock and Atomic types in Rust
Mitsunori Komatsu
 
Signposts
SignpostsSignposts
Signposts
Heidi Howard
 
What the &~#@&lt;!? (Memory Management in Rust)
What the &~#@&lt;!? (Memory Management in Rust)What the &~#@&lt;!? (Memory Management in Rust)
What the &~#@&lt;!? (Memory Management in Rust)
David Evans
 
OOP in Rust
OOP in RustOOP in Rust
OOP in Rust
KENZ_gelsoft
 
Redox OS
Redox OSRedox OS
Redox OS
Norbert Melzer
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engine
Bruno Abinader
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
Ruslan Shevchenko
 
Kernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring NaughtKernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring Naught
David Evans
 
Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...
Anil Madhavapeddy
 
Ocaml
OcamlOcaml
Camomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlCamomile : A Unicode library for OCaml
Camomile : A Unicode library for OCaml
Yamagata Yoriyuki
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
Jordan Open Source Association
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)
Anil Madhavapeddy
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
Haskell - Functional Programming
Haskell - Functional ProgrammingHaskell - Functional Programming
Haskell - Functional Programming
Giovane Berny Possebon
 
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOMERuby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Julien Fitzpatrick
 
Introduction to Rust Programming Language
Introduction to Rust Programming LanguageIntroduction to Rust Programming Language
Introduction to Rust Programming Language
Robert 'Bob' Reyes
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
Michel Rijnders
 
計算数学
計算数学計算数学
計算数学
blackenedgold
 

Viewers also liked (20)

Rust Synchronization Primitives
Rust Synchronization PrimitivesRust Synchronization Primitives
Rust Synchronization Primitives
 
Performance Comparison of Mutex, RWLock and Atomic types in Rust
Performance Comparison of Mutex, RWLock and  Atomic types in RustPerformance Comparison of Mutex, RWLock and  Atomic types in Rust
Performance Comparison of Mutex, RWLock and Atomic types in Rust
 
Signposts
SignpostsSignposts
Signposts
 
What the &~#@&lt;!? (Memory Management in Rust)
What the &~#@&lt;!? (Memory Management in Rust)What the &~#@&lt;!? (Memory Management in Rust)
What the &~#@&lt;!? (Memory Management in Rust)
 
OOP in Rust
OOP in RustOOP in Rust
OOP in Rust
 
Redox OS
Redox OSRedox OS
Redox OS
 
Servo: The parallel web engine
Servo: The parallel web engineServo: The parallel web engine
Servo: The parallel web engine
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Kernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring NaughtKernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring Naught
 
Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...
 
Ocaml
OcamlOcaml
Ocaml
 
Camomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlCamomile : A Unicode library for OCaml
Camomile : A Unicode library for OCaml
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Haskell - Functional Programming
Haskell - Functional ProgrammingHaskell - Functional Programming
Haskell - Functional Programming
 
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOMERuby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
Ruby is Awesome and Rust is Awesome and Building a Game in Both is AWESOME
 
Introduction to Rust Programming Language
Introduction to Rust Programming LanguageIntroduction to Rust Programming Language
Introduction to Rust Programming Language
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
計算数学
計算数学計算数学
計算数学
 

Similar to Hey! There's OCaml in my Rust!

Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
Chiyoung Song
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
Tushar Pal
 
PLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptxPLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptx
Richard Martens
 
Python first day
Python first dayPython first day
Python first day
farkhand
 
Python first day
Python first dayPython first day
Python first day
MARISSTELLA2
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
AbdulRazaqAnjum
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
Should i Go there
Should i Go thereShould i Go there
Should i Go there
Shimi Bandiel
 
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
kamalsmail1
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
Python by ganesh kavhar
Python by ganesh kavharPython by ganesh kavhar
Python by ganesh kavhar
Savitribai Phule Pune University
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
GDSCKYAMBOGO
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
The Ring programming language version 1.6 book - Part 16 of 189
The Ring programming language version 1.6 book - Part 16 of 189The Ring programming language version 1.6 book - Part 16 of 189
The Ring programming language version 1.6 book - Part 16 of 189
Mahmoud Samir Fayed
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
Adeel Hamid
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
justbasics.pdf
justbasics.pdfjustbasics.pdf
justbasics.pdf
DrRajkumarKhatri
 

Similar to Hey! There's OCaml in my Rust! (20)

Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
PLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptxPLSQL-OO [SOUG 2022].pptx
PLSQL-OO [SOUG 2022].pptx
 
Python first day
Python first dayPython first day
Python first day
 
Python first day
Python first dayPython first day
Python first day
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
17-Arrays-And-Files-kkkkkkkkkkkkkkk.pptx
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
Python by ganesh kavhar
Python by ganesh kavharPython by ganesh kavhar
Python by ganesh kavhar
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
The Ring programming language version 1.6 book - Part 16 of 189
The Ring programming language version 1.6 book - Part 16 of 189The Ring programming language version 1.6 book - Part 16 of 189
The Ring programming language version 1.6 book - Part 16 of 189
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
justbasics.pdf
justbasics.pdfjustbasics.pdf
justbasics.pdf
 

Recently uploaded

Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
norina2645
 
How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024
TaskSprint | Employee Efficiency Software
 
Odoo E-commerce website development guides
Odoo E-commerce website development guidesOdoo E-commerce website development guides
Odoo E-commerce website development guides
jhkdigitalmarketing
 
Artificial intelligence in customer services or chatbots
Artificial intelligence  in customer services or chatbotsArtificial intelligence  in customer services or chatbots
Artificial intelligence in customer services or chatbots
kayash1656
 
ThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and DjangoThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and Django
akshesh doshi
 
ERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in CoimbatoreERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in Coimbatore
Nextskill Technologies
 
IoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdf
IoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdfIoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdf
IoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdf
mohitd6
 
welcome to presentation on Google Apps
welcome to   presentation on Google Appswelcome to   presentation on Google Apps
welcome to presentation on Google Apps
AsifKarimJim
 
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
902basic
 
High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...
High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...
High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...
singhlata50dh
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
ThousandEyes
 
Blockchain in Agricultural Traceability Use Cases in 2024.pdf
Blockchain in Agricultural Traceability Use Cases in 2024.pdfBlockchain in Agricultural Traceability Use Cases in 2024.pdf
Blockchain in Agricultural Traceability Use Cases in 2024.pdf
Natsoft Corporation
 
VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...
VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...
VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...
jealousviolet
 
Il Data Streaming per un’AI real-time di nuova generazione
Il Data Streaming per un’AI real-time di nuova generazioneIl Data Streaming per un’AI real-time di nuova generazione
Il Data Streaming per un’AI real-time di nuova generazione
confluent
 
Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...
Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...
Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...
aslasdfmkhan4750
 
React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
SSTech System
 
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdfAI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
Daniel Zivkovic
 
TEQnation 2024: Sustainable Software: May the Green Code Be with You
TEQnation 2024: Sustainable Software: May the Green Code Be with YouTEQnation 2024: Sustainable Software: May the Green Code Be with You
TEQnation 2024: Sustainable Software: May the Green Code Be with You
marcofolio
 

Recently uploaded (20)

Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
 
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
 
How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024
 
Odoo E-commerce website development guides
Odoo E-commerce website development guidesOdoo E-commerce website development guides
Odoo E-commerce website development guides
 
Artificial intelligence in customer services or chatbots
Artificial intelligence  in customer services or chatbotsArtificial intelligence  in customer services or chatbots
Artificial intelligence in customer services or chatbots
 
ThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and DjangoThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and Django
 
ERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in CoimbatoreERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in Coimbatore
 
IoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdf
IoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdfIoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdf
IoT In Manufacturing_ Use Cases, Benefits, and Challenges.pdf
 
welcome to presentation on Google Apps
welcome to   presentation on Google Appswelcome to   presentation on Google Apps
welcome to presentation on Google Apps
 
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
Private Girls Call Navi Mumbai 🛵🚡9820252231 💃 Choose Best And Top Girl Servic...
 
High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...
High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...
High Girls Call Chennai 000XX00000 Provide Best And Top Girl Service And No1 ...
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
 
Blockchain in Agricultural Traceability Use Cases in 2024.pdf
Blockchain in Agricultural Traceability Use Cases in 2024.pdfBlockchain in Agricultural Traceability Use Cases in 2024.pdf
Blockchain in Agricultural Traceability Use Cases in 2024.pdf
 
VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...
VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...
VVIP Girls Call Mumbai 9910780858 Provide Best And Top Girl Service And No1 i...
 
Il Data Streaming per un’AI real-time di nuova generazione
Il Data Streaming per un’AI real-time di nuova generazioneIl Data Streaming per un’AI real-time di nuova generazione
Il Data Streaming per un’AI real-time di nuova generazione
 
Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...
Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...
Independent Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class H...
 
React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
 
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdfAI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
 
TEQnation 2024: Sustainable Software: May the Green Code Be with You
TEQnation 2024: Sustainable Software: May the Green Code Be with YouTEQnation 2024: Sustainable Software: May the Green Code Be with You
TEQnation 2024: Sustainable Software: May the Green Code Be with You
 

Hey! There's OCaml in my Rust!

  • 1. HEY!There’s OCaml In My Rust! Kel Cecil @praisechaos
  • 5. It's a functional programming language... # let double x = x * 2 in List.map double [ 1; 2; 3 ];; - : int list = [2; 4; 6] • OCaml is an almost pure functional programming language by default. • Functions are first-class citizens.
  • 6. ... and an imperative programming language... let update_collectable_value order new_value = order.old_value <- order.current_value; order.current_value <- new_value; order • It can be convenient to be able to code in the imperative style. • OCaml includes imperative constructs like for and while loops.
  • 7. ... and an object-oriented language! class ['a] queue init = object val mutable q: 'a list = init method enqueue item = q <- q @ item end;; • OCaml can also be object-oriented if needed.
  • 8. OCaml powers some pretty sweet stuff. • MirageOS: Unikernel tech recently acquired by Docker • Flow: A static type checker for JavaScript • Hack: A programming languages for Facebook's HHVM • and...
  • 9. Rust's first compiler! • rustboot was written in OCaml • Replaced for Rust 0.7
  • 10. Rust is pretty excellent too! • Guaranteed Memory Safety • Threads without data races • Incredibly fast • Crazy awesome potential
  • 11. Rust was inspired by OCaml in a few interesting ways!
  • 12. Let's start with a simple, imperative OCaml program • Define a type named collectable_value that olds the previous value and current value of an item. • Provide a function to update the current value and update the old value. • Have a "main" function to create the record and update the value.
  • 13. Starting with our type type collectable_value = { mutable old_value: float; mutable current_value: float; } • A record is a collection of values stored together as a data type. • Values are immutable by default but can be marked as mutable.
  • 14. Adding our first function let update_collectable_value collectable new_value = collectable.old_value <- collectable.current_value; collectable.current_value <- new_value; collectable • Define a function with a let-binding. • Accepts a collectablevalue record (collectable) and a float (newvalue). • Updates and returns the record.
  • 15. Adding a "main" let _ = let pinball_machine = { old_value = 0.0; current_value = 800.00; } in update_collectable_value pinball_machine 900.0 • Underscore discards the return value. • This let-binding allows us to execute code at the top level.
  • 16. Anything seem a little Rust-y to you? type collectable_value = { mutable old_value: float; mutable current_value: float; } let update_collectable_value order new_value = order.old_value <- order.current_value; order.current_value <- new_value; order let _ = let pinball_machine = { old_value = 0.0; current_value = 800.00; } in update_collectable_value pinball_machine 900.0
  • 17. Semicolon Separation in OCaml let update_collectable_value collectable new_value = collectable.old_value <- collectable.current_value; collectable.current_value <- new_value; collectable • Notice the semi-colons separating the expressions? • The last expression is the return value for the function. • Look familiar?
  • 18. Statements in Rust fn greeting() -> String { let greeting = "Hello, there!"; String::from(greeting) // Return value from fn } • Rust code is mostly statements. • Most common statements are • declaring a variable • using an expression with a semi-colon • Last expression omitting the semi-colon is returned.
  • 19. What is Type Inference? • Automatic deduction of the data type of an expression.
  • 20. Rust's Type Inference // Rust knows that name is a String. let name = "Kel!" • Rust's type inference is loosely based on the Hindley-Milner algorithm4 . • Extensions were added to use accommodate subtyping. 4 https://github.com/rust-lang/rust/blob/master/src/librustc/infer/README.md
  • 21. OCaml's Type Inference (* OCaml also knows this is a string. *) let name = "Kel!" • ML originally used the Hindley-Milner algorithm. • OCaml's implementation works through solving constraints. • Tons of research hours poured into their algorithm(s)5 5 https://www.cis.upenn.edu/~sweirich/icfp-plmw15/slides/pottier.pdf
  • 22. Workshop: Binary Search Tree • Follow along in your IDEs! • Learn about binary search trees here: • https://en.wikipedia.org/wiki/Binary_search_tree • Check out the examples • https://github.com/kelcecil/rust-ocaml-workshop
  • 23. Building our Tree Structure OCaml, then Rust.
  • 24. Tree in OCaml type tree;; • Types in OCaml are defined with the type keyword.
  • 25. Tree in OCaml type tree = Empty ;; • We need to represent a node that does not exist. • We'll represent this as Empty.
  • 26. Tree in OCaml type tree = | Empty | Node ;; • We also want to represent a node that exists. • We'll represent this as node.
  • 27. Tree in OCaml type 'a tree = | Empty | Node of 'a * 'a tree * 'a tree ;; • Our node must have a key, a left child, and a right child. • Node now contains generic 'a that is our key. • We also have two values of tree presenting our left and right leaves.
  • 28. Algebraic Data Types • Composite type formed from other types • Common types of Algebraic Types • Product Types • Sum Types
  • 29. Product Types • Compound types in a structure • Operands of the product are types • Structure is determined by fixed order of operands
  • 30. (* Record *) type person = {name: string; age: int};; let kel = {name = "Kel"; age = 30};; (* Tuple *) let next_obsession = ("Dead Rising 4", 59.99);; Tuples and records are product types in OCaml
  • 31. let my_love = ("Rust", 9001) • Tuples are product types in Rust • There's also the unit () type • Tuple with no operands.
  • 32. Sum Types type 'a tree = | Empty | Node of 'a * 'a tree * 'a tree ;; • Multiple classes of values called variants. • Each class has it's own constructor. • Class represents it's own concept
  • 33. Tree in Rust enum Tree { Empty } • Algebraic data types are enums in Rust. • We start with defining Empty.
  • 34. enum Tree<T>{ Empty, Node(T, Box<Tree<T>>, Box<Tree<T>>) } • Node is a generic variable for the key, a left leaf, and a right leaf. • Recursive structures must be boxed1 . • We want the size of the Tree to be bounded. • Pointer using Box allocates memory on the heap. 1 https://doc.rust-lang.org/std/boxed/
  • 35. Recap: Rust and OCaml Tree Structures6 type 'a tree = | Empty | Node of 'a * 'a tree * 'a tree ;; enum Tree<T>{ Empty, Node(T, Box<Tree<T>>, Box<Tree<T>>) } 6 https://github.com/kelcecil/rust-ocaml-workshop/tree/master/workshop/01-structure
  • 36. Writing a depth function
  • 37. depth (OCaml using Pattern Matching) let rec depth tree = match tree with | Empty -> 0 | Node(_, left, right) -> 1 + max (depth left) (depth right) ;; • let defines a variable or function in OCaml. • rec denotes a recursive function. • The match keyword matches by data type.
  • 38. depth (OCaml using function) let rec depth = function | Empty -> 0 | Node(_, left, right) -> 1 + max (depth left) (depth right) ;; • OCaml functions can also be defined using the function keyword. • function has built in pattern matching for types. • This syntax is a bit more concise.
  • 39. Unit Test for depth (OCaml) open OUnit (* tree type here *) (* depth function here *) let test_tree = Node(5, Node(3, Empty, Empty), Empty) let tree_depth _ = assert_equal 2 (depth test_tree) let suite = "Binary Tree Tests" >::: ["tree_depth" >:: tree_depth] let _ = run_test_tt_main suite
  • 40. Running OCaml Tests ocamlfind ocamlc -package oUnit -linkpkg -o <output_binary> <source_file>
  • 41. depth (Rust) impl<T> Tree<T> where T: PartialOrd { fn depth(&self) -> usize { match *self { Tree::Empty => 0, Tree::Node(_, ref left, ref right) => 1 + max(left.depth(), right.depth()) } } } • Restricting our generic to PartialOrd lets us choose our key type similarly to OCaml.
  • 42. Unit Test for depth (Rust) #[test] fn depth_test() { let tree = Tree::Node(5, Box::new( Tree::Node(4,Box::new(Tree::Empty), Box::new(Tree::Empty) )), Box::new(Tree::Empty)); assert!(tree.depth() == 2) }
  • 43. Running Rust Unit Tests rustc --test <source_file>
  • 44. tl;dr • OCaml's inspiration for Rust can been seen in: • Semicolon Statement Separation • Type Inference • Algebraic Data Types • Pattern Matching • Rust and OCaml are both totally awesome.
  • 45. Time for you to try! • Adjust the our tree implementations to hold values. • Write insert functions for OCaml and Rust! • Write member functions for OCaml and Rust!
  • 46. Stumped? No problem. • https://github.com/kelcecil/rust-ocaml-workshop • Clone the repository and experiment! • Check out the other random examples in the repository. • Ask for help!
  • 47. Branching in OCaml OCaml has an if statement like so2 : if <boolean_condition> then <expression> else if <boolean_condition> then <expression> else <expression> 2 https://ocaml.org/learn/tutorials/ifstatementsloopsandrecursion.html