-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
542 lines (478 loc) · 11.5 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style type="text/css">
@import url(http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body { font-family: 'Droid Serif'; }
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
img {
width: 100%;
height: auto;
}
img#kixer-logo {
width: 130px;
height: 54px;
}
ul, ol {
margin: 6px 0 6px 0;
}
li {
margin: 0 0 12px 0;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# A Scala view of Rust
<image src="slides/kixer-logo.png" id="kixer-logo" />
https://koeninger.github.io/scala-view-of-rust
I'm a Rust noob... take what I say with a grain of salt
---
## Scala = Java + ML
* Need access to JVM libraries
* But still want a sane modern language
- static typing and inference
- controlled mutability
- algebraic data types
- closures
- pattern matching
- parametric polymorphism / generics
- ad hoc polymorphism / typeclasses
- macros
* OK with cost of garbage collection, latency, memory footprint
---
## Rust = C + ML
* Need predictable latency / footprint, can't afford garbage collection
* But still want a sane modern language
- static typing and inference
- controlled mutability
- algebraic data types
- closures
- pattern matching
- parametric polymorphism / generics
- ad hoc polymorphism / typeclasses
- macros
* OK with cost of having to think more about memory
- because the language helps you get it right, usually at **compile time**
---
## Stuff that Rust doesn't have (besides GC)
* null pointer exceptions
* data races
* Tuple22 limit
* catching exceptions
* inheritance
* higher kinded types
* a good REPL
---
## Hello: Scala
```scala
import scala.io.StdIn
object Hello {
def main(args: Array[String]) {
println("What's your name?")
StdIn.readLine() match {
case name: String => println(s"Hello, $name")
case _ => println("Sorry, I didn't hear your null pointer")
}
}
}
```
---
## Hello: Rust
```rust
use std::io;
fn main() {
println!("What's your name?");
let mut name = String::new();
match io::stdin().read_line(&mut name) {
Ok(_) => println!("Hello, {}", name),
Err(e) => println!("Sorry, {}", e)
}
}
```
---
## Building your code: Scala
* install JVM + sbt
* sbt run
* sbt console
* look for libraries on maven central or github, add them to build.sbt
* sbt test (after deciding on a ~~religion~~ test framework)
* sbt ~test
* install JVM on your server
* sbt assembly
* copy fat jar to server and run it
---
## Building your code: Rust
* install cargo
* cargo run
* feel sad about the lack of a repl :(
* look for libraries on crates.io or github, add them to Cargo.toml
* cargo test (using the simple built-in test framework)
* cargo watch
* check that build architecture matches server (or cross compile)
* cargo build --release
* copy statically linked binary to server and run it
---
## Null Pointers: Scala
```scala
class Bad {
def blowup(opt: Option[Int]) {
opt.map(x => println(s"I got an $x"))
}
val x = Some(23)
// scala would complain if this was a local variable instead
var y: Option[Int] = _
blowup(x)
// RUNTIME error: java.lang.NullPointerException
blowup(y)
}
```
---
## Null Pointers: Rust
```rust
fn no_blowup(opt: &Option<u32>) {
opt.map(|x| println!("I got an {:?}", x));
}
fn main() {
let x = Some(23);
// COMPILE warning: single-assignment variable doesn't need to be mutable
let mut y;
no_blowup(&x);
// COMPILE error: use of possibly uninitialized variable: `y`
// no_blowup(&y);
// COMPILE error: mismatched types
// y = std::ptr::null();
// no_blowup(&y);
y = None;
no_blowup(&y);
}
```
---
## Ownership: Rust
```rust
fn main() {
let three = outer();
println!("Leaving main"); // Dropping three
}
fn outer() -> Entity {
let one = Entity::new(1);
let two = Entity::new(2);
let three = Entity::new(3);
inner(two);
// COMPILE error: use of moved value
//println!("this would be use-after-free {:?}", two);
println!("Leaving Outer");
three // Dropping one
}
fn inner(e: Entity) {
println!("Leaving Inner"); // Dropping two
}
```
---
## Borrowing references: Rust
* two kinds of references
- shared reference: **&**
- mutable reference: **&mut**
* two rules
- a reference can't live longer than the thing it refers to
- a mutable reference can't have an alias (another live reference)
--
* enforced at compile time via subtyping of lifetime parameters: **'a**
* 'a is a **subtype** of 'b if 'a outlives 'b, aka 'a is **bigger** in scope than 'b
* lifetime parameters are usually inferred
---
## Reference that would live too long: Rust
```rust
fn as_str(e: &Entity) -> &str {
let s = format!("{:?}", e);
// COMPILE error: s does not live long enough
&s
}
```
--
```
// this isn't valid syntax, but an approximate desugaring
fn as_str<'a>(e: &'a Entity) -> &'a str {
'b {
let s = format!("{:?}", e);
return &'a s
}
}
```
---
## Aliased mutable reference: Rust
```rust
let mut vector = Vec::with_capacity(1);
vector.push(23);
let head = &vector[0];
// COMPILE error:
// cannot borrow vector as mutable because it is also borrowed as immutable
vector.push(42);
println!("head is {}", head);
```
--
```
// this isn't valid syntax, but an approximate desugaring
'a {
let mut vector = Vec::with_capacity(1);
vector.push(23);
'b {
let head: &'b i32 = Index::index::<'b>(&'b vector, 0)
'c {
// COMPILE error:
// cannot borrow vector as mutable because it is also borrowed as immutable
Vec::push(&'c mut vector, 42);
}
println!("head is {}", head);
}
}
```
---
## Borrow checker caveats: Rust
* doesn't guarantee against leaks (but neither does GC)
* when you need multiple mutable references, e.g. a graph, can either
- use runtime reference counted types (Rc) and mutability checks (RefCell)
- manage raw pointers yourself, encapsulated in unsafe { } blocks
---
## Data races: Scala
```scala
class CountEvensVsOdds(reporter: ActorRef) extends Actor {
val state = Array(0, 0)
def receive = {
case x: Int =>
if (x % 2 == 0) {
state(0) = state(0) + 1
} else {
state(1) = state(1) + 1
}
if ((state(0) + state(1)) % 10 == 0) {
// RUNTIME error: sharing mutable state between threads
reporter ! state
}
}
```
---
## Data races: Rust
```rust
fn count_evens_vs_odds(rx: Receiver<i32>, tx: Sender<&Vec<i32>>) {
let mut state = vec![0, 0];
loop {
let x = rx.recv().unwrap();
if x % 2 == 0 {
state[0] += 1;
} else {
state[1] += 1;
}
if (state[0] + state[1]) % 10 == 0 {
// COMPILE error: state does not live long enough
tx.send(&state).unwrap();
}
}
}
```
---
## Algebraic Data Types: Scala
```scala
/** A product type */
case class Point(
val x: Double,
val y: Double
) {
def distanceFromOrigin = {
math.sqrt(math.pow(x, 2) + math.pow(y, 2))
}
}
/** A sum type */
sealed abstract class Option[+A] extends Product with Serializable {
}
case object None extends Option[Nothing] {
def isEmpty = true
}
final case class Some[+A](x: A) extends Option[A] {
def isEmpty = false
}
```
---
## Algebraic Data Types: Rust
```rust
/// A product type
pub struct Point {
x: f64,
y: f64
}
impl Point {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
/// A sum type
pub enum Option<T> {
None, // This will be optimized to a null pointer
Some(T)
}
impl<T> Option<T> {
#[inline]
pub fn is_some(&self) -> bool {
match *self {
Some(_) => true,
None => false,
}
}
}
```
---
## Typeclasses: Scala
```scala
object Json {
trait ToJson[T] {
def toJsonStr(t: T): String
}
implicit object IntToJson extends ToJson[Int] {
def toJsonStr(i: Int) = i.toString
}
implicit def ArrayToJson[S: ToJson] = new ToJson[Array[S]] {
def toJsonStr(a: Array[S]) = {
a.map(x => implicitly[ToJson[S]].toJsonStr(x)).
mkString("[", ", ", "]")
}
}
implicit class ToJsonSyntax[S: ToJson](s: S) {
def toJsonStr = implicitly[ToJson[S]].toJsonStr(s)
}
}
object TypeclassExample {
import Json._
def main(args: Array[String]) {
val v = Array(1, 2, 3, 4)
println(v.toJsonStr)
}
}
```
---
## Typeclasses: Rust
```rust
trait ToJson {
fn to_json_str(&self) -> String;
}
impl ToJson for i32 {
fn to_json_str(&self) -> String {
self.to_string()
}
}
impl<T: ToJson> ToJson for Vec<T> {
fn to_json_str(&self) -> String {
format!("[{}]",
self.iter().map(|x| x.to_json_str()).
collect::<Vec<_>>().join(", "))
}
}
fn main() {
let v = vec![1, 2, 3, 4];
println!("{}", v.to_json_str());
}
```
---
## Newtype: Scala
```scala
case class Inches(self: Int) extends AnyVal {
def +(other: Inches): Inches = {
Inches(self + other.self)
}
}
case class Feet(self: Int) extends AnyVal {
def +(other: Feet): Feet = {
Feet(self + other.self)
}
}
def main(args: Array[String]) {
val i = Inches(1)
val i2 = Inches(2)
val f = Feet(1)
val f2 = Feet(2)
println(s"f + f2 = ${f + f2}")
println(s"i + i2 = ${i + i2}")
// COMPILE error: type mismatch
//println(s"f + i = ${f + i}")
}
```
---
## Newtype: Rust
```rust
#[derive(Debug)]
struct Inches(i32);
impl Add for Inches {
type Output = Inches;
fn add(self, other: Inches) -> Inches {
Inches(self.0 + other.0)
}
}
#[derive(Debug)]
struct Feet(i32);
impl Add for Feet {
type Output = Feet;
fn add(self, other: Feet) -> Feet {
Feet(self.0 + other.0)
}
}
fn main() {
let i = Inches(1);
let i2 = Inches(2);
let f = Feet(1);
let f2 = Feet(2);
println!("f + f2 = {:?}", f + f2);
println!("i + i2 = {:?}", i + i2);
// COMPILE error: mismatched types
//println!("f + i = {:?}", f + i);
}
```
---
## Macros: Rust
```rust
macro_rules! newtype_number {
($i:ident $t:ty) => {
#[derive(Debug)]
struct $i($t);
impl Add for $i {
type Output = $i;
fn add(self, other: $i) -> $i {
$i(self.0 + other.0)
}
}
}
}
newtype_number!(Inches i32);
newtype_number!(Feet i32);
fn main() {
let i = Inches(1);
let i2 = Inches(2);
let f = Feet(1);
let f2 = Feet(2);
println!("f + f2 = {:?}", f + f2);
println!("i + i2 = {:?}", i + i2);
}
```
---
## Resources
* [Code for these slides](https://github.com/koeninger/scala-view-of-rust)
* [The Rust Book](http://doc.rust-lang.org/book/)
* [Rust 101](http://www.ralfj.de/projects/rust-101/main.html)
* [Learning Rust With Entirely Too Many Linked Lists](http://cglab.ca/~abeinges/blah/too-many-lists/book)
* [The Rustonomicon](http://doc.rust-lang.org/nomicon/)
</textarea>
<script src="slides/remark-latest.min.js">
</script>
<script>
var slideshow = remark.create();
</script>
</body>
</html>