2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Introduction to Functional Programming in Rust写経

Posted at

YOW! Lambda Jam 2019 - Amit Dev - Introduction to Functional Programming in Rustという動画を見たら、簡潔なコードサンプルがたくさん紹介されていたのでメモする。

YOW! Lambda Jam 2019 - Amit Dev - Introduction to Functional Programming in Rust

0 value

Rust
enum Void {}
Haskell
data Void

1 value

Rust
enum Unit {
    Unit
}
// or
()
Haskell
data Unit = Unit
-- or
()

1 + 1

Rust
enum Direction {
    Up,
    Down
}
// or
bool
Haskell
data Direction = Up | Down
-- or
Boolean

1 + A

Rust
enum Option<A> {
    Some(A),
    None
}
Haskell
data Maybe a = Just a | Nothing

A * Boolean

Rust
(A, B)
// or
struct Tuple { a: A, b: B }
Haskell
data (a, b) = (a, b)

L = 1 + AL

Rust
enum List<A> {
    Nil,
    Cons(A, Box<List<A>>)
}

Rustでは、Boxを使って可変を表現する。

Haskell
data List a =
            Nil |
            Cons a (List a)

Pattern Matching

Rust
struct Person {
    name: String,
    address: Option<String>
}
//...
match person {
    Person { name, address : Some(s) }
        => (name, s.len()),
    Person { name, address : None}
        => (name, 0)
}

Pattern Matching

Rust
fn age_type(age: Option<i32>) -> & static str {
    match age {
        Some(val) if val < 0    => "Negative",
        Some(val @ 0 ... 18)    => "Less than 18",
        Some(val) if val > 150  => "Over 150",
        Some(val)               => "Adult",
        None                    => "Empty"
    }
}

Factorial - Take 1

Rust
fn factorial(n: u64) -> u64 {
    match n {
        0 | 1 => 1,
        n     => n * factorial(n - 1),
    }
}

Factorial - Take 2

Rust
fn factorial(n: u64) -> u64 {
    (1..n+1).fold(1, |acc, i| acc * i)
}
Rust
use std::ops::Mul;

fn factorial(n:u64) -> u64 {
    (1..n+1).fold(1, Mul::mul)
}

振り返り

  1. Youtubeにはもっとたくさんの簡潔なコード例が紹介されているようだ。手になじむように書いていこう。
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?