SlideShare una empresa de Scribd logo
1 de 84
Descargar para leer sin conexión
Rust v.s TS
Variable
• Typescript
• Rust
const num = 123;
num = 456;
// Uncaught TypeError: Assignment to constant variable.
console.log(`The value of num is: ${num}`);
let num = 123;
num = 456;
// error[E0384]: cannot assign twice to immutable variable `num`
println!("The value of numMut is: {}", num);
Variable
• Typescript
• Rust
let mut numMut = 123;
numMut = 456;
println!("The value of numMut is: {}", numMut);
let numMut = 123;
numMut = 456;
console.log(`The value of numMut is: ${numMut}`);
• Typescript
• Rust
fn add(x: i32, y: i32) -> i32 {
x + y
}
add(1, 2); // 3
function add(x: number, y: number) {
return x + y;
}
add(1, 2); // 3
Function
Function
• Typescript
• Rust
function return_undefined(x: number, y: number): void {
const added = x + y;
}
return_undefined(1, 2); // undefined
fn return_unit(x: i32, y: i32) -> () {
let added = x + y;
}
return_unit(1, 2); // ()
Lambda expression
• Typescript
• Rust
let add2 = (x: number) => x + 2;


let add3 = (x: number) => {

return x + 3;

}
let add2 = |x| x + 2;
let add3 = |x: i32| -> i32 {
x + 3
};
Rust closure
• Typescript
• Rust
let a = 4;


let addA = x => x + a;
let a = 4;
let add_a = |x| x + a;
If else / Ternary
• Typescript
• Rust
let state: string = null;
if (condition) {
state = "a";
} else {
state = "b";
}
let state2 = condition ? "a" : "b";
let condition = true;
let state = if condition { "a" } else { "b" };
• Typescript
const options = {
cond1: false,
cond2: true,
propA: "a",
propB: "b"
};
let state = options.cond1 ? options.propA
: options.cond2
? doSomeThing(options.propB)
: doAnotherThing("c");
function doSomeThing(str: string) {
return "print: ".concat(str);
}
function doAnotherThing(str: string) {
return "print: ".concat(str);
}
Real World Case Study
• Typescript
const options = {
cond1: false,
cond2: true,
propA: "a",
propB: "b"
};
let state = options.cond1 ? options.propA
: options.cond2
? doSomeThing(options.propB)
: doAnotherThing("c");
function doSomeThing(str: string) {
return "print: ".concat(str);
}
function doAnotherThing(str: string) {
return "print: ".concat(str);
}
Real World Case Study
// print: b
• Rust
Real World Case Study
let options = Options {
cond1: false,
cond2: true,
propA: String::from("a"),
propB: String::from("b")
};
let state = if options.cond1 {
options.propA
} else if options.cond2 {
do_some_thing(&options.propB)
} else {
do_another_thing(&String::from(""))
};
println!("{:?}", state); // print: b
• Rust
Real World Case Study
let options = Options {
cond1: false,
cond2: true,
propA: String::from("a"),
propB: String::from("b")
};
let state = if options.cond1 {
options.propA
} else if options.cond2 {
do_some_thing(&options.propB)
} else {
do_another_thing(&String::from(""))
};
println!("{:?}", state); // print: b
• Rust
Real World Case Study
let options = Options {
cond1: false,
cond2: true,
propA: String::from("a"),
propB: String::from("b")
};
let state = if options.cond1 {
options.propA
} else if options.cond2 {
do_some_thing(&options.propB)
} else {
do_another_thing(&String::from(""))
};
println!("{:?}", state); // print: b
• Rust
Real World Case Study
let options = Options {
cond1: false,
cond2: true,
propA: String::from("a"),
propB: String::from("b")
};
let state = if options.cond1 {
options.propA
} else if options.cond2 {
do_some_thing(&options.propB)
} else {
do_another_thing(&String::from(""))
};
println!("{:?}", state); // print: b
Object v.s Struct
• Typescript
interface User {
username: string;
email: string;
active: boolean;
sign_in_count: number;
}
const user1: User = {
username: 'someusername123',
email: 'someone@example.com',
active: true,
sign_in_count: 1,
};
Object v.s Struct
• Typescript
class User {
constructor(
public username: string,
public email: string,
public active: boolean,,
public sign_in_count: number,
) {}
}
const user = new User(
'someusername123',
'someone@example.com',
true,
1
);
Object v.s Struct
• Rust
struct User {
username: String,
email: String,
active: bool,
sign_in_count: u64,
}
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
Interface / Implement
• Typescript
interface IDuck {
name: string;
quack(): void;
walk(): void;
}
class Duck implements IDuck {
public name: string;
constructor(name: string) {
this.name = name;
}
quack() {
console.log(`${this.name} quacking!`);
}
walk() {
console.log(`${this.name} walking!`);
}
}
Interface / Implement
• Rust
trait DuckTrait {
fn quack(&self);
fn walk(&self);
}
struct Duck {
name: &'static str
}
impl Duck for DuckTrait {
fn quack(&self) {
println!("{} quacking!", self.name);
}
fn walk(&self) {
println!("{} walking!", self.name);
}
}
• Typescript
• Rust
let duck = Duck { name: "Duck A" };
duck.quack(); //Duck A quacking!
duck.walk(); // Duck A walking!
let duck = new Duck("Duck A”);
duck.quack(); // Duck A quacking!
duck.walk(); // Duck A walking!
Interface / Implement
Collection and Iterator
Collection and For Syntax
• Typescript
• Rust
let arr = [4, 5, 6];
for(let item of arr) {
console.log(`print: ${item}`);
}
let vec = vec![4,5,6];
for item in vec.iter() {
println!("print: {}", item);
}
// print: 4
// print: 5
// print: 6
Collection and For Syntax
• Typescript
• Rust
let arr = [4, 5, 6];
for(let item of arr) {
console.log(`print: ${item}`);
}
let vec = vec![4,5,6];
for item in vec.iter() {
println!("print: {}", item);
}
// print: 4
// print: 5
// print: 6
Collection and For Syntax
• Typescript
• Rust
let arr = [4, 5, 6];
for(let item of arr) {
console.log(`print: ${item}`);
}
let vec = vec![4,5,6];
for item in vec.iter() {
println!("print: {}", item);
}
// print: 4
// print: 5
// print: 6
Iterator
• Invoke next method
let mut iter = vec![4,5,6].iter();
println!("{:?}", iter.next()); // Some(4)
println!("{:?}", iter.next()); // Some(5)
println!("{:?}", iter.next()); // Some(6)
• Iterator Trait
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
Typescript Array
• map 、 filter
let mapped: number[] = [1,2,3].map(x => x + 1); // [2,3,4]
let filtered: number[] = [1,2,3].filter(x => x > 2); // [3]
Typescript Array
• map 、 filter
• reduce、some、find、forEach…
let mapped: number[] = [1,2,3].map(x => x + 1); // [2,3,4]
let filtered: number[] = [1,2,3].filter(x => x > 2); // [3]
let hasBiggerThanOne = [1, 2, 3].some(x => x > 1); // true
let sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0); // 6
let finded = [1, 2, 4].find(x => x > 2); // 4
[1,2,3].forEach(x => console.log(x)); // undefined
Rust Vector
• map 、 filter
let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4]
let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3]
Rust Vector
• map 、 filter
let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4]
let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3]
• map 、 filter
• any、fold、find、forEach…
let has_bigger_than_one = vec![1, 2, 3].iter().any(|x| x > 1); // true
let sum = vec![1,2,3].iter().fold(0, |acc, curr| acc + curr); // 6
let finded = vec![1, 2, 4].iter().find(|&x| x > 2); // Some(4)
let for_eached = vec![1,2,3].iter().for_each(|x| println!("{}", x)); // ()
let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4]
let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3]
Rust Vector
• map 、 filter
• any、fold、find、forEach…
let has_bigger_than_one = vec![1, 2, 3].iter().any(|x| x > 1); // true
let sum = vec![1,2,3].iter().fold(0, |acc, curr| acc + curr); // 6
let finded = vec![1, 2, 4].iter().find(|&x| x > 2); // Some(4)
let for_eached = vec![1,2,3].iter().for_each(|x| println!("{}", x)); // ()
let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4]
let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3]
Rust Vector
Step by step
let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
Step by step
let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
Step by step
let map_iter = vec![1,2,3].iter().map(|x| x + 1); // Map { iter: Iter([1, 2, 3]) }
Lazy Compute !
let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
Step by step
let map_iter = vec![1,2,3].iter().map(|x| x + 1); // Map { iter: Iter([1, 2, 3]) }
let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
Step by step
let map_iter = vec![1,2,3].iter().map(|x| x + 1); // Map { iter: Iter([1, 2, 3]) }
let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4]
let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
Map Adapter
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn map<B, F>(self, f: F) -> Map<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> B,
{
Map::new(self, f)
}
https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#721-724
Map Adapter
#[stable(feature = "rust1", since = "1.0.0")]
impl<B, I: Iterator, F> Iterator for Map<I, F>
where
F: FnMut(I::Item) -> B,
{
type Item = B;
#[inline]
fn next(&mut self) -> Option<B> {
self.iter.next().map(&mut self.f)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
...
}
https://doc.rust-lang.org/src/core/iter/adapters/map.rs.html#59-63
Consumer
#[inline]
#[stable(feature = "rust1", since = “1.0.0")]
...
fn collect<B: FromIterator<Self::Item>>(self) -> B
where
Self: Sized,
{
FromIterator::from_iter(self)
}
https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#92-114
Consumer
pub trait FromIterator<A>: Sized {
...
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
}
https://doc.rust-lang.org/beta/src/core/result.rs.html#1577-1627
#[inline]
#[stable(feature = "rust1", since = “1.0.0")]
...
fn collect<B: FromIterator<Self::Item>>(self) -> B
where
Self: Sized,
{
FromIterator::from_iter(self)
}
Custom Customer
https://doc.rust-lang.org/std/iter/trait.FromIterator.html
#[derive(Debug)]
struct MyCollection(Vec<i32>);
impl MyCollection {
fn new() -> MyCollection {
MyCollection(Vec::new())
}
fn add(&mut self, elem: i32) {
self.0.push(elem);
}
}
Custom Customer
https://doc.rust-lang.org/std/iter/trait.FromIterator.html
impl FromIterator<i32> for MyCollection {
fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
let mut c = MyCollection::new();
for i in iter {
c.add(i);
}
c
}
}
JS Array’s Limit
https://twitter.com/mgechev/status/1280523754615926784?s=20
JS Array’s Limit
https://twitter.com/mgechev/status/1280523754615926784?s=20
JS Array’s Limit
https://twitter.com/mgechev/status/1280523754615926784?s=20
JS Array’s Limit
https://twitter.com/mgechev/status/1280523754615926784?s=20
JS library’s Solution
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
import { append, compose, map, take, tap, transduce } from 'ramda';
let data = [1, 2, 3, 4, 5];
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
let step = (acc, curr) => append(acc, curr);
let init_val = [];
let result = transduce(transducer, step, init_val)(data);
console.log(`---Result---`, result);
JS library’s Solution
import { append, compose, map, take, tap, transduce } from 'ramda';
let data = [1, 2, 3, 4, 5];
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
let step = (acc, curr) => append(acc, curr);
let init_val = [];
let result = transduce(transducer, step, init_val)(data);
console.log(`---Result---`, result);
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
JS library’s Solution
import { append, compose, map, take, tap, transduce } from 'ramda';
let data = [1, 2, 3, 4, 5];
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
let step = (acc, curr) => append(acc, curr);
let init_val = [];
let result = transduce(transducer, step, init_val)(data);
console.log(`---Result---`, result);
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
JS library’s Solution
import { append, compose, map, take, tap, transduce } from 'ramda';
let data = [1, 2, 3, 4, 5];
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
let step = (acc, curr) => append(acc, curr);
let init_val = [];
let result = transduce(transducer, step, init_val)(data);
console.log(`---Result---`, result);
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
JS library’s Solution
import { append, compose, map, take, tap, transduce } from 'ramda';
let data = [1, 2, 3, 4, 5];
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
let step = (acc, curr) => append(acc, curr);
let init_val = [];
let result = transduce(transducer, step, init_val)(data);
console.log(`---Result---`, result);
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
JS library’s Solution
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
import { append, compose, map, take, tap, transduce } from 'ramda';
let data = [1, 2, 3, 4, 5];
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
let step = (acc, curr) => append(acc, curr);
let init_val = [];
let result = transduce(transducer, step, init_val)(data);
console.log(`---Result---`, result);
Rust’s Solution
println!("---Start---");
let result: Vec<i32> = vec![1, 2, 3, 4, 5].iter()
.inspect(|x| println!("iter_value: {}", x))
.map(|x| x + 1)
.take(2)
.collect();
println!("---Result---");
println!("{:?}", result);
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
Rust Version
println!("---Start---");
let result: Vec<i32> = vec![1, 2, 3, 4, 5].iter()
.inspect(|x| println!("iter_value: {}", x))
.map(|x| x + 1)
.take(2)
.collect();
println!("---Result---");
println!("{:?}", result);
-—-Start——
iter_value: 1
iter_value: 2
—-Result—-
[2, 3]
JS Array’s Limit
JS Array’s Limit
https://twitter.com/mgechev/status/1280523754615926784?s=20
Zero Cost Iterator Abstraction
https://doc.rust-lang.org/book/ch13-04-performance.html
Think with set and function
Think with set and function
map
Family Member’s
age
let toAge = |p| p.age
!
👶
#
$ 73
42
1
37
73
42
1
37
Think with set and function
map
let afterOneYear= |age| age + 1
74
43
2
38
Think with set and function
filter
let elders= |age| age > 40
74
43
2
38
74
43
Think with set and function
1
2
4
3
A
4
5
7
6
B
8
9
11
10
C
f: A -> B g: B -> C
let add_three = |a| a + 3 let add_four= |a| a + 4
Think with set and function
1
2
4
3
A
8
9
11
10
C
g ∘ f : A -> C
let add_seven= compose!(add_four, add_three);
• Delcarative: describes what you want, but
not how to achieve it.
• Divide and conquer: split big question to
multiple small questions.
Benefit of composition
• Think with data: focus on your goal.
Use macro for your
abstraction
Declarative Macro
let vector: Vec<i32> = vec![1, 2, 3];
#[macro_export]
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
Procedural Macros
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 0, y: 0 };
println!(Debug Point: {:?}”, point);
// Debug: Point { x: 0, y: 0 }
Procedural Macros
https://doc.rust-lang.org/book/ch19-06-macros.html
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::R
f.debug_struct("Point")
.field("x", &self.x)
.field("y", &self.y)
.finish()
}
}
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 0, y: 0 };
println!(Debug Point: {:?}”, point);
// Debug: Point { x: 0, y: 0 }
Rust Compiler Flow
https://doc.rust-lang.org/beta/src/core/result.rs.html#1577-1627
Inspect Compiled Code
0.50
Use Case: Variadic Function
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
Use Case: Variadic Function
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
function compose(f, g) {
return x => f(g(x));
};
Use Case: Variadic Function
let transducer = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2)
);
function compose(f, g) {
return x => f(g(x));
};
function compose(f, g, h) {
return x => f(g(h(x)));
};
Use Case: Variadic Function
function compose(…fns) {
return (arg) => fns.reduceRight((acc, fn) => fn(acc), args);
}
let newFunction = compose(
tap(x => console.log(`iter_value: ${x}`)),
map(x => x + 1),
take(2),
tap(x => console.log(`taked_value: ${x}`)),
);
Use Case: Variadic Function
macro_rules! compose {
($($fns:expr),+) => {
move |arg| compose!(@inner arg, $($fns),+)
};
(@inner $x:expr, $f:expr, $($fns: expr),+) => {
$f(compose!(@inner $x, $($fns),+))
};
(@inner $x:expr, $f:expr) => {
$f($x)
};
}
$($fns:expr),*: repeat functions
*: zero or more repetitions
+: one or more repetitions
$f:expr: matched function expression
Use Case: Variadic Function
macro_rules! compose {
($($fns:expr),+) => {
move |arg| compose!(@inner arg, $($fns),+)
};
(@inner $x:expr, $f:expr, $($fns: expr),+) => {
$f(compose!(@inner $x, $($fns),+))
};
(@inner $x:expr, $f:expr) => {
$f($x)
};
}
fn main() {
let f1 = |x: i32| x + 1;
let f2 = |y: i32| y + 2;
let f3 = |z: i32| z + 3;
let f4 = compose!(f3, f2, f1);
println!("{:?}", f4(4))
}
Reuse composed function
fn f1(x: i32) -> i32 { x + 1 }
fn f2(y: i32) -> i32 { y + 2 }
fn f3(z: i32) -> i32 { z + 3 }
pub fn f4(input: i32) -> i32 {
compose!(f3, f2, f1)(input)
}
Reuse composed function
pub fn precededc<I, O1, O2, E: ParseError<I>, F, G>(
input: I,
first: F,
second: G,
) -> IResult<I, O2, E>
where
F: Fn(I) -> IResult<I, O1, E>,
G: Fn(I) -> IResult<I, O2, E>,
{
preceded(first, second)(input)
}
Debug your macro
Trace the expansion of macros
#![feature(trace_macros)]
...
fn main() {
let f1 = |x: i32| x + 1;
let f2 = |y: i32| y + 2;
let f3 = |z: i32| z + 3;
trace_macros!(true);
let f4 = compose!(f3, f2, f1);
trace_macros!(false);
println!("{:?}", f4(4))
}
Trace the expansion of macros
#![feature(trace_macros)]
...
fn main() {
let f1 = |x: i32| x + 1;
let f2 = |y: i32| y + 2;
let f3 = |z: i32| z + 3;
trace_macros!(true);
let f4 = compose!(f3, f2, f1);
trace_macros!(false);
println!("{:?}", f4(4))
}
note: trace_macro
--> src/main.rs:18:14
|
18 | let f4 = compose!(f3, f2, f1);
| ^^^^^^^^^^^^^^^^^^^^
|
= note: expanding `compose! { f3, f2, f1 }`
= note: to `move | arg | compose! (@inner arg, f3, f2, f1)`
= note: expanding `compose! { @inner arg, f3, f2, f1 }`
= note: to `f3 (compose! (@inner arg, f2, f1))`
= note: expanding `compose! { @inner arg, f2, f1 }`
= note: to `f2 (compose! (@inner arg, f1))`
= note: expanding `compose! { @inner arg, f1 }`
= note: to `f1 (arg)`
Inspect Expanded Macro
Inspect Expanded Macro
rustup run nightly cargo rustc -- -Z unstable-options --pretty=expanded
Inspect Expanded Macro
rustup run nightly cargo rustc -- -Z unstable-options --pretty=expanded
fn main() {
let f1 = |x: i32| x + 1;
let f2 = |y: i32| y + 2;
let f3 = |z: i32| z + 3;
();
let f4 = move |arg| f3(f2(f1(arg)));
();
{
...
}
}

Más contenido relacionado

La actualidad más candente

Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! aleks-f
 
D3 svg & angular
D3 svg & angularD3 svg & angular
D3 svg & angular500Tech
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Dimitrios Platis
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012aleks-f
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real Worldosfameron
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 

La actualidad más candente (20)

Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
Functional Scala 2020
Functional Scala 2020Functional Scala 2020
Functional Scala 2020
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
D3 svg & angular
D3 svg & angularD3 svg & angular
D3 svg & angular
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
 
Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012Dynamic C++ Silicon Valley Code Camp 2012
Dynamic C++ Silicon Valley Code Camp 2012
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
Lambda expressions in C++
Lambda expressions in C++Lambda expressions in C++
Lambda expressions in C++
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Ricky Bobby's World
Ricky Bobby's WorldRicky Bobby's World
Ricky Bobby's World
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
 
Lenses
LensesLenses
Lenses
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 

Similar a Coscup2021-rust-toturial

Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?jonbodner
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 
bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018AlastairRobertson9
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In RubyRoss Lawley
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection apitrygvea
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to GoJaehue Jang
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티JaeYeoul Ahn
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JSRitesh Kumar
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapHoward Lewis Ship
 

Similar a Coscup2021-rust-toturial (20)

Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Javascript
JavascriptJavascript
Javascript
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018
 
Groovy
GroovyGroovy
Groovy
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Groovy collection api
Groovy collection apiGroovy collection api
Groovy collection api
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
Go 프로그래밍 소개 - 장재휴, DomainDriven커뮤니티
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JS
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Modern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter BootstrapModern Application Foundations: Underscore and Twitter Bootstrap
Modern Application Foundations: Underscore and Twitter Bootstrap
 

Último

SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Último (20)

SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Coscup2021-rust-toturial

  • 2. Variable • Typescript • Rust const num = 123; num = 456; // Uncaught TypeError: Assignment to constant variable. console.log(`The value of num is: ${num}`); let num = 123; num = 456; // error[E0384]: cannot assign twice to immutable variable `num` println!("The value of numMut is: {}", num);
  • 3. Variable • Typescript • Rust let mut numMut = 123; numMut = 456; println!("The value of numMut is: {}", numMut); let numMut = 123; numMut = 456; console.log(`The value of numMut is: ${numMut}`);
  • 4. • Typescript • Rust fn add(x: i32, y: i32) -> i32 { x + y } add(1, 2); // 3 function add(x: number, y: number) { return x + y; } add(1, 2); // 3 Function
  • 5. Function • Typescript • Rust function return_undefined(x: number, y: number): void { const added = x + y; } return_undefined(1, 2); // undefined fn return_unit(x: i32, y: i32) -> () { let added = x + y; } return_unit(1, 2); // ()
  • 6. Lambda expression • Typescript • Rust let add2 = (x: number) => x + 2; 
 let add3 = (x: number) => {
 return x + 3;
 } let add2 = |x| x + 2; let add3 = |x: i32| -> i32 { x + 3 };
  • 7. Rust closure • Typescript • Rust let a = 4; 
 let addA = x => x + a; let a = 4; let add_a = |x| x + a;
  • 8. If else / Ternary • Typescript • Rust let state: string = null; if (condition) { state = "a"; } else { state = "b"; } let state2 = condition ? "a" : "b"; let condition = true; let state = if condition { "a" } else { "b" };
  • 9. • Typescript const options = { cond1: false, cond2: true, propA: "a", propB: "b" }; let state = options.cond1 ? options.propA : options.cond2 ? doSomeThing(options.propB) : doAnotherThing("c"); function doSomeThing(str: string) { return "print: ".concat(str); } function doAnotherThing(str: string) { return "print: ".concat(str); } Real World Case Study
  • 10. • Typescript const options = { cond1: false, cond2: true, propA: "a", propB: "b" }; let state = options.cond1 ? options.propA : options.cond2 ? doSomeThing(options.propB) : doAnotherThing("c"); function doSomeThing(str: string) { return "print: ".concat(str); } function doAnotherThing(str: string) { return "print: ".concat(str); } Real World Case Study // print: b
  • 11. • Rust Real World Case Study let options = Options { cond1: false, cond2: true, propA: String::from("a"), propB: String::from("b") }; let state = if options.cond1 { options.propA } else if options.cond2 { do_some_thing(&options.propB) } else { do_another_thing(&String::from("")) }; println!("{:?}", state); // print: b
  • 12. • Rust Real World Case Study let options = Options { cond1: false, cond2: true, propA: String::from("a"), propB: String::from("b") }; let state = if options.cond1 { options.propA } else if options.cond2 { do_some_thing(&options.propB) } else { do_another_thing(&String::from("")) }; println!("{:?}", state); // print: b
  • 13. • Rust Real World Case Study let options = Options { cond1: false, cond2: true, propA: String::from("a"), propB: String::from("b") }; let state = if options.cond1 { options.propA } else if options.cond2 { do_some_thing(&options.propB) } else { do_another_thing(&String::from("")) }; println!("{:?}", state); // print: b
  • 14. • Rust Real World Case Study let options = Options { cond1: false, cond2: true, propA: String::from("a"), propB: String::from("b") }; let state = if options.cond1 { options.propA } else if options.cond2 { do_some_thing(&options.propB) } else { do_another_thing(&String::from("")) }; println!("{:?}", state); // print: b
  • 15. Object v.s Struct • Typescript interface User { username: string; email: string; active: boolean; sign_in_count: number; } const user1: User = { username: 'someusername123', email: 'someone@example.com', active: true, sign_in_count: 1, };
  • 16. Object v.s Struct • Typescript class User { constructor( public username: string, public email: string, public active: boolean,, public sign_in_count: number, ) {} } const user = new User( 'someusername123', 'someone@example.com', true, 1 );
  • 17. Object v.s Struct • Rust struct User { username: String, email: String, active: bool, sign_in_count: u64, } let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, };
  • 18. Interface / Implement • Typescript interface IDuck { name: string; quack(): void; walk(): void; } class Duck implements IDuck { public name: string; constructor(name: string) { this.name = name; } quack() { console.log(`${this.name} quacking!`); } walk() { console.log(`${this.name} walking!`); } }
  • 19. Interface / Implement • Rust trait DuckTrait { fn quack(&self); fn walk(&self); } struct Duck { name: &'static str } impl Duck for DuckTrait { fn quack(&self) { println!("{} quacking!", self.name); } fn walk(&self) { println!("{} walking!", self.name); } }
  • 20. • Typescript • Rust let duck = Duck { name: "Duck A" }; duck.quack(); //Duck A quacking! duck.walk(); // Duck A walking! let duck = new Duck("Duck A”); duck.quack(); // Duck A quacking! duck.walk(); // Duck A walking! Interface / Implement
  • 22. Collection and For Syntax • Typescript • Rust let arr = [4, 5, 6]; for(let item of arr) { console.log(`print: ${item}`); } let vec = vec![4,5,6]; for item in vec.iter() { println!("print: {}", item); } // print: 4 // print: 5 // print: 6
  • 23. Collection and For Syntax • Typescript • Rust let arr = [4, 5, 6]; for(let item of arr) { console.log(`print: ${item}`); } let vec = vec![4,5,6]; for item in vec.iter() { println!("print: {}", item); } // print: 4 // print: 5 // print: 6
  • 24. Collection and For Syntax • Typescript • Rust let arr = [4, 5, 6]; for(let item of arr) { console.log(`print: ${item}`); } let vec = vec![4,5,6]; for item in vec.iter() { println!("print: {}", item); } // print: 4 // print: 5 // print: 6
  • 25. Iterator • Invoke next method let mut iter = vec![4,5,6].iter(); println!("{:?}", iter.next()); // Some(4) println!("{:?}", iter.next()); // Some(5) println!("{:?}", iter.next()); // Some(6) • Iterator Trait trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; }
  • 26. Typescript Array • map 、 filter let mapped: number[] = [1,2,3].map(x => x + 1); // [2,3,4] let filtered: number[] = [1,2,3].filter(x => x > 2); // [3]
  • 27. Typescript Array • map 、 filter • reduce、some、find、forEach… let mapped: number[] = [1,2,3].map(x => x + 1); // [2,3,4] let filtered: number[] = [1,2,3].filter(x => x > 2); // [3] let hasBiggerThanOne = [1, 2, 3].some(x => x > 1); // true let sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0); // 6 let finded = [1, 2, 4].find(x => x > 2); // 4 [1,2,3].forEach(x => console.log(x)); // undefined
  • 28. Rust Vector • map 、 filter let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4] let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3]
  • 29. Rust Vector • map 、 filter let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4] let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3]
  • 30. • map 、 filter • any、fold、find、forEach… let has_bigger_than_one = vec![1, 2, 3].iter().any(|x| x > 1); // true let sum = vec![1,2,3].iter().fold(0, |acc, curr| acc + curr); // 6 let finded = vec![1, 2, 4].iter().find(|&x| x > 2); // Some(4) let for_eached = vec![1,2,3].iter().for_each(|x| println!("{}", x)); // () let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4] let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3] Rust Vector
  • 31. • map 、 filter • any、fold、find、forEach… let has_bigger_than_one = vec![1, 2, 3].iter().any(|x| x > 1); // true let sum = vec![1,2,3].iter().fold(0, |acc, curr| acc + curr); // 6 let finded = vec![1, 2, 4].iter().find(|&x| x > 2); // Some(4) let for_eached = vec![1,2,3].iter().for_each(|x| println!("{}", x)); // () let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4] let filtered: Vec<i32> = vec![1,2,3].iter().filter(|&y| y > 2).collect(); // [3] Rust Vector
  • 32. Step by step let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
  • 33. Step by step let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
  • 34. Step by step let map_iter = vec![1,2,3].iter().map(|x| x + 1); // Map { iter: Iter([1, 2, 3]) } Lazy Compute ! let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
  • 35. Step by step let map_iter = vec![1,2,3].iter().map(|x| x + 1); // Map { iter: Iter([1, 2, 3]) } let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
  • 36. Step by step let map_iter = vec![1,2,3].iter().map(|x| x + 1); // Map { iter: Iter([1, 2, 3]) } let mapped: Vec<i32> = vec![1,2,3].iter().map(|x| x + 1).collect(); // [2,3,4] let iter = vec![1,2,3].iter(); // Iter([1, 2, 3])
  • 37. Map Adapter #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn map<B, F>(self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(Self::Item) -> B, { Map::new(self, f) } https://doc.rust-lang.org/src/core/iter/traits/iterator.rs.html#721-724
  • 38. Map Adapter #[stable(feature = "rust1", since = "1.0.0")] impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B, { type Item = B; #[inline] fn next(&mut self) -> Option<B> { self.iter.next().map(&mut self.f) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } ... } https://doc.rust-lang.org/src/core/iter/adapters/map.rs.html#59-63
  • 39. Consumer #[inline] #[stable(feature = "rust1", since = “1.0.0")] ... fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized, { FromIterator::from_iter(self) } https://doc.rust-lang.org/src/core/iter/traits/collect.rs.html#92-114
  • 40. Consumer pub trait FromIterator<A>: Sized { ... fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self; } https://doc.rust-lang.org/beta/src/core/result.rs.html#1577-1627 #[inline] #[stable(feature = "rust1", since = “1.0.0")] ... fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized, { FromIterator::from_iter(self) }
  • 41. Custom Customer https://doc.rust-lang.org/std/iter/trait.FromIterator.html #[derive(Debug)] struct MyCollection(Vec<i32>); impl MyCollection { fn new() -> MyCollection { MyCollection(Vec::new()) } fn add(&mut self, elem: i32) { self.0.push(elem); } }
  • 42. Custom Customer https://doc.rust-lang.org/std/iter/trait.FromIterator.html impl FromIterator<i32> for MyCollection { fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self { let mut c = MyCollection::new(); for i in iter { c.add(i); } c } }
  • 47. JS library’s Solution -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3] import { append, compose, map, take, tap, transduce } from 'ramda'; let data = [1, 2, 3, 4, 5]; let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); let step = (acc, curr) => append(acc, curr); let init_val = []; let result = transduce(transducer, step, init_val)(data); console.log(`---Result---`, result);
  • 48. JS library’s Solution import { append, compose, map, take, tap, transduce } from 'ramda'; let data = [1, 2, 3, 4, 5]; let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); let step = (acc, curr) => append(acc, curr); let init_val = []; let result = transduce(transducer, step, init_val)(data); console.log(`---Result---`, result); -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3]
  • 49. JS library’s Solution import { append, compose, map, take, tap, transduce } from 'ramda'; let data = [1, 2, 3, 4, 5]; let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); let step = (acc, curr) => append(acc, curr); let init_val = []; let result = transduce(transducer, step, init_val)(data); console.log(`---Result---`, result); -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3]
  • 50. JS library’s Solution import { append, compose, map, take, tap, transduce } from 'ramda'; let data = [1, 2, 3, 4, 5]; let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); let step = (acc, curr) => append(acc, curr); let init_val = []; let result = transduce(transducer, step, init_val)(data); console.log(`---Result---`, result); -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3]
  • 51. JS library’s Solution import { append, compose, map, take, tap, transduce } from 'ramda'; let data = [1, 2, 3, 4, 5]; let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); let step = (acc, curr) => append(acc, curr); let init_val = []; let result = transduce(transducer, step, init_val)(data); console.log(`---Result---`, result); -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3]
  • 52. JS library’s Solution -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3] import { append, compose, map, take, tap, transduce } from 'ramda'; let data = [1, 2, 3, 4, 5]; let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); let step = (acc, curr) => append(acc, curr); let init_val = []; let result = transduce(transducer, step, init_val)(data); console.log(`---Result---`, result);
  • 53. Rust’s Solution println!("---Start---"); let result: Vec<i32> = vec![1, 2, 3, 4, 5].iter() .inspect(|x| println!("iter_value: {}", x)) .map(|x| x + 1) .take(2) .collect(); println!("---Result---"); println!("{:?}", result); -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3]
  • 54. Rust Version println!("---Start---"); let result: Vec<i32> = vec![1, 2, 3, 4, 5].iter() .inspect(|x| println!("iter_value: {}", x)) .map(|x| x + 1) .take(2) .collect(); println!("---Result---"); println!("{:?}", result); -—-Start—— iter_value: 1 iter_value: 2 —-Result—- [2, 3]
  • 57. Zero Cost Iterator Abstraction https://doc.rust-lang.org/book/ch13-04-performance.html
  • 58. Think with set and function
  • 59. Think with set and function map Family Member’s age let toAge = |p| p.age ! 👶 # $ 73 42 1 37
  • 60. 73 42 1 37 Think with set and function map let afterOneYear= |age| age + 1 74 43 2 38
  • 61. Think with set and function filter let elders= |age| age > 40 74 43 2 38 74 43
  • 62. Think with set and function 1 2 4 3 A 4 5 7 6 B 8 9 11 10 C f: A -> B g: B -> C let add_three = |a| a + 3 let add_four= |a| a + 4
  • 63. Think with set and function 1 2 4 3 A 8 9 11 10 C g ∘ f : A -> C let add_seven= compose!(add_four, add_three);
  • 64. • Delcarative: describes what you want, but not how to achieve it. • Divide and conquer: split big question to multiple small questions. Benefit of composition • Think with data: focus on your goal.
  • 65. Use macro for your abstraction
  • 66. Declarative Macro let vector: Vec<i32> = vec![1, 2, 3]; #[macro_export] macro_rules! vec { ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); $( temp_vec.push($x); )* temp_vec } }; }
  • 67. Procedural Macros #[derive(Debug)] struct Point { x: i32, y: i32, } let point = Point { x: 0, y: 0 }; println!(Debug Point: {:?}”, point); // Debug: Point { x: 0, y: 0 }
  • 68. Procedural Macros https://doc.rust-lang.org/book/ch19-06-macros.html use std::fmt; struct Point { x: i32, y: i32, } impl fmt::Debug for Point { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::R f.debug_struct("Point") .field("x", &self.x) .field("y", &self.y) .finish() } } #[derive(Debug)] struct Point { x: i32, y: i32, } let point = Point { x: 0, y: 0 }; println!(Debug Point: {:?}”, point); // Debug: Point { x: 0, y: 0 }
  • 71. Use Case: Variadic Function let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) );
  • 72. Use Case: Variadic Function let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); function compose(f, g) { return x => f(g(x)); };
  • 73. Use Case: Variadic Function let transducer = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2) ); function compose(f, g) { return x => f(g(x)); }; function compose(f, g, h) { return x => f(g(h(x))); };
  • 74. Use Case: Variadic Function function compose(…fns) { return (arg) => fns.reduceRight((acc, fn) => fn(acc), args); } let newFunction = compose( tap(x => console.log(`iter_value: ${x}`)), map(x => x + 1), take(2), tap(x => console.log(`taked_value: ${x}`)), );
  • 75. Use Case: Variadic Function macro_rules! compose { ($($fns:expr),+) => { move |arg| compose!(@inner arg, $($fns),+) }; (@inner $x:expr, $f:expr, $($fns: expr),+) => { $f(compose!(@inner $x, $($fns),+)) }; (@inner $x:expr, $f:expr) => { $f($x) }; } $($fns:expr),*: repeat functions *: zero or more repetitions +: one or more repetitions $f:expr: matched function expression
  • 76. Use Case: Variadic Function macro_rules! compose { ($($fns:expr),+) => { move |arg| compose!(@inner arg, $($fns),+) }; (@inner $x:expr, $f:expr, $($fns: expr),+) => { $f(compose!(@inner $x, $($fns),+)) }; (@inner $x:expr, $f:expr) => { $f($x) }; } fn main() { let f1 = |x: i32| x + 1; let f2 = |y: i32| y + 2; let f3 = |z: i32| z + 3; let f4 = compose!(f3, f2, f1); println!("{:?}", f4(4)) }
  • 77. Reuse composed function fn f1(x: i32) -> i32 { x + 1 } fn f2(y: i32) -> i32 { y + 2 } fn f3(z: i32) -> i32 { z + 3 } pub fn f4(input: i32) -> i32 { compose!(f3, f2, f1)(input) }
  • 78. Reuse composed function pub fn precededc<I, O1, O2, E: ParseError<I>, F, G>( input: I, first: F, second: G, ) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(I) -> IResult<I, O2, E>, { preceded(first, second)(input) }
  • 80. Trace the expansion of macros #![feature(trace_macros)] ... fn main() { let f1 = |x: i32| x + 1; let f2 = |y: i32| y + 2; let f3 = |z: i32| z + 3; trace_macros!(true); let f4 = compose!(f3, f2, f1); trace_macros!(false); println!("{:?}", f4(4)) }
  • 81. Trace the expansion of macros #![feature(trace_macros)] ... fn main() { let f1 = |x: i32| x + 1; let f2 = |y: i32| y + 2; let f3 = |z: i32| z + 3; trace_macros!(true); let f4 = compose!(f3, f2, f1); trace_macros!(false); println!("{:?}", f4(4)) } note: trace_macro --> src/main.rs:18:14 | 18 | let f4 = compose!(f3, f2, f1); | ^^^^^^^^^^^^^^^^^^^^ | = note: expanding `compose! { f3, f2, f1 }` = note: to `move | arg | compose! (@inner arg, f3, f2, f1)` = note: expanding `compose! { @inner arg, f3, f2, f1 }` = note: to `f3 (compose! (@inner arg, f2, f1))` = note: expanding `compose! { @inner arg, f2, f1 }` = note: to `f2 (compose! (@inner arg, f1))` = note: expanding `compose! { @inner arg, f1 }` = note: to `f1 (arg)`
  • 83. Inspect Expanded Macro rustup run nightly cargo rustc -- -Z unstable-options --pretty=expanded
  • 84. Inspect Expanded Macro rustup run nightly cargo rustc -- -Z unstable-options --pretty=expanded fn main() { let f1 = |x: i32| x + 1; let f2 = |y: i32| y + 2; let f3 = |z: i32| z + 3; (); let f4 = move |arg| f3(f2(f1(arg))); (); { ... } }