多重ディスパッチ入門
===
<!-- .element: style="font-size: 300%" -->
<!-- .slide: data-background-color="rgba(102,130,223,0.3)" -->
2019/05/11 JuliaTokai \#02
antimon2(後藤 俊介)
Note:
Multiple Dispatch 簡易チュートリアル
----
<!-- .slide: data-background-color="rgba(102,130,223,0.3)" -->
## お品書き
+ お前誰よ?
+ 簡単なJuliaの紹介
+ 多重ディスパッチとは?
---
<!-- .slide: data-background-color="rgba(102,130,223,0.3)" -->
# お前誰よ?
----
<!-- .slide: data-background-color="rgba(102,130,223,0.3)" -->
## 自己紹介
+ 名前:後藤 俊介
+ 所属:**[有限会社 来栖川電算](https://www.kurusugawa.jp)**
+ コミュニティ:**[JuliaTokai](https://juliatokai.connpass.com/)**, **[機械学習名古屋](https://machine-learning.connpass.com/)**, [Python東海](https://connpass.com/series/292/), Ruby東海, …
+ 言語:**[Julia](https://julialang.org)**, Python, Scala(勉強中), Ruby, …
+ ![Twitter](https://i.imgur.com/HqouMIg.png)<!-- .element: class="plain" style="vertical-align:middle;background:transparent" --> [@antimon2](https://twitter.com/antimon2) / ![Facebook](https://i.imgur.com/01nPd37.png)<!-- .element: class="plain" style="vertical-align:middle;background:transparent" --> [antimon2](https://www.facebook.com/antimon2)
+ ![Github](https://i.imgur.com/yBKtii5.png)<!-- .element: class="plain" style="vertical-align:middle;background:transparent" --> [antimon2](https://github.com/antimon2/) / ![Qiita](https://i.imgur.com/FxHMi64.png)<!-- .element: class="plain" style="vertical-align:middle;background:transparent" --> [@antimon2](http://qiita.com/antimon2)
Note:
今日は(も?)大っぴらに Julia の話ができるっ
----
<!-- .slide: data-background-color="rgba(102,130,223,0.3)" -->
[![有限会社来栖川電算](https://i.imgur.com/8Kuhfel.png)
https://www.kurusugawa.jp](https://www.kurusugawa.jp)
Note:
普段は Python で仕事してますっ
---
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
# <small>簡単な</small><br>Julia の紹介
Note:
Julia の紹介っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
[![Julia](https://upload.wikimedia.org/wikipedia/commons/6/69/Julia_prog_language.svg)<!-- .element: style="background:white;max-width:80%" -->](https://julialang.org)
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
## Julia とは?(1)
+ [The Julia Language](https://julialang.org)
+ 2018/08/08 に正式版 v1.0 がリリース!
+ 最新 v1.1.0(2019/01/21)
+ 科学技術計算に強い!
+ 動作が速い!(LLVM JIT コンパイル)
Note:
ググるときはなるべく [julialang](https://www.google.co.jp/search?q=julialang) で!
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
## Julia とは?(2)
> + Rのように中身がぐちゃぐちゃでなく、
> + Rubyのように遅くなく、
> + Lispのように原始的またはエレファントでなく、
> + Prologのように変態的なところはなく、
> + Javaのように硬すぎることはなく、
> + Haskellのように抽象的すぎない
>
> ほどよい言語である
<!-- .element: style="font-size:66%" -->
引用元:http://www.slideshare.net/Nikoriks/julia-28059489/8
<!-- .element: style="font-size:71%" -->
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
## Julia とは?(3)
> + C のように高速だけど、
Ruby のような動的型付言語である
> + Lisp のようにプログラムと同等に扱えるマクロがあって、しかも
Matlab のような直感的な数式表現もできる
> + Python のように総合的なプログラミングができて、
R のように統計処理も得意で、
Perl のように文字列処理もできて、
Matlab のように線形代数もできて、
shell のように複数のプログラムを組み合わせることもできる
> + 超初心者にも習得は簡単で、
超上級者の満足にも応えられる
> + インタラクティブにも動作して、コンパイルもできる
<!-- .element: style="font-size:50%" -->
([Why We Created Julia](http://julialang.org/blog/2012/02/why-we-created-julia) から抜粋・私訳)
<!-- .element: style="font-size:71%" -->
Note:
いろんな言語の「いいとこどり」言語!ってことでっ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
## 要するに
<!-- .element: style="font-size:300%" -->
+ 動的言語なのに速い!
+ 文法も覚えやすい!
+ 数値計算に強い!
<!-- .element: style="font-size:180%" -->
Note:
機械学習とかにも持って来いっ!
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
## 主な機能
<!-- .element: style="font-size:280%" -->
+ **[多重ディスパッチ](https://docs.julialang.org/en/v1/manual/methods/)**
+ [動的型システム](https://docs.julialang.org/en/v1/manual/types/)
+ [並行・並列処理](https://docs.julialang.org/en/v1/manual/parallel-computing/)、コルーチン
+ [組込パッケージマネージャ](https://docs.julialang.org/en/v1/stdlib/Pkg/)
<!-- .element: style="font-size:160%" -->
Note:
今日はこの **多重ディスパッチ** の話をしますっ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
## 文法・関数
Note:
以降、ほぼ過去スライドからのコピペ。すっ飛ばして先へ進んで戴いてもOKっ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 基本的な演算
```julia
julia> 1 + 2 - 3 * 4 # 四則演算(除算以外)
-9
julia> 7 / 5 # `整数 / 整数` の結果は浮動小数
1.4
julia> 7 ÷ 5 # `整数 ÷ 整数` の結果は整数
1
julia> 2 ^ 10 # 冪乗は `^`
1024
julia> 123 & 234 | 345 # 論理積 / 論理和
376
julia> 123 ⊻ 234 # 排他的論理和(==`xor(123, 234)`)
145
```
<!-- .element: style="font-size:46%" -->
Note:
整数同士の除算は実数になりますっ
整数除算演算子 `÷` が別に存在します(Python の `//` 相当)っ
また冪乗も(`**` ではなく)`^` ですっ
`⊻` は `\xor`+<kbd>Tab</kbd> または `\veebar`+<kbd>Tab</kbd> で変換できますっ
ちなみに先ほどの `÷` も `\div`+<kbd>Tab</kbd>で(基本的に ${\rm \TeX}$ の書式)っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 配列
```julia
julia> a = [1, 2, 3, 4, 5]
5-element Array{Int64,1}:
1
2
3
4
5
julia> a[1] # Julia は 1-origin
1
julia> println(a[2:3]) # 範囲指定は両端含む
[2, 3]
```
<!-- .element: style="font-size:50%" -->
Note:
1-origin であることに注意すればあとは普通の配列っ
あと `a:b` は範囲(`Range`)の記法。両端を含む(Ruby の `a..b` と同じ)っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 配列の内包表記 (1)
```julia
julia> a = [n^2 for n=1:5]
5-element Array{Int64,1}:
1
4
9
16
25
julia> A = [x+10y for y=1:3, x=1:3]
3×3 Array{Int64,2}:
11 12 13
21 22 23
31 32 33
```
<!-- .element: style="font-size:50%" -->
Note:
内包表記の記法は Python に類似っ
かつ、`for` にカンマ区切りで複数のイテレータを渡すことで2次元以上の配列も作成可能っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 配列の内包表記 (2)
```julia
julia> [(a,b,c) for c=1:15,b=1:15,a=1:15 if a^2+a*b+b^2==c^2]
6-element Array{Tuple{Int64,Int64,Int64},1}:
(3, 5, 7)
(5, 3, 7)
(6, 10, 14)
(7, 8, 13)
(8, 7, 13)
(10, 6, 14)
```
Note:
Python と同様に `if` で条件を指定することも可能っ
あと Python と同様、`[○ for ○=○]` を `(○ for ○=○)` と書くと配列ではなくて `Generator` が返りますっ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### ベクトル
```julia
julia> x = [1., 2., 3.]; y = [3., 1., 2.];
julia> x + y # `x .+ y` と書いても同じ(elementwise operation)
[4., 3., 5.]
julia> x .* y # これは `x * y` と書くとNG
[3., 2., 6.]
julia> using LinearAlgebra
julia> x ⋅ y # 内積(dot積、`dot(x, y)` と書いても同じ)
11.0
julia> x × y # 外積(cross積、`cross(x, y)` と書いても同じ)
[1., 7., -5.]
```
<!-- .element: style="font-size:50%" -->
Note:
Julia では実は1次元配列がベクトルの扱いっ
`⋅` は `\cdot`+<kbd>Tab</kbd>、`×` は `\times`+<kbd>Tab</kbd>(これらを利用するには `using LinearAlgebra` 必要)っ
あとこれらや先ほどの `÷` や `⊻` などのように、ASCIIの範囲を超えたUnicode文字の演算子(そのほとんどが $\TeX$ 由来)が Julia にはたくさんあります(他には例えば比較演算子の `≤` `≥` や、集合の要素 `∈` や包含関係 `⊆` などなど)
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 行列
```julia
julia> A = [1 2; 3 4] # この記法は MATLAB/Octave 由来
2×2 Array{Int64,2}:
1 2
3 4
julia> A' # `○'` は転置行列の記法(これも MATLAB/Octave 由来)
2×2 LinearAlgebra.Adjoint{Int64,Array{Int64,2}}:
1 3
2 4
julia> transpose(A) # 正確には転置行列はこっち
2×2 LinearAlgebra.Transpose{Int64,Array{Int64,2}}:
1 3
2 4
```
<!-- .element: style="font-size:50%" -->
Note:
Julia では2次元配列が行列の扱いっ
あと `○.'` という書式は廃止されました(`transpose(A)` 使ってね)っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 行列の演算
```julia
julia> A = [1 2; 3 4]; B = [3 0; 0 6];
julia> A + B # A .+ B でも同様
2×2 Array{Int64,2}:
4 2
3 10
julia> A * B # matrix multiply
2×2 Array{Int64,2}:
3 12
9 24
julia> A .* B # elementwise multiply
2×2 Array{Int64,2}:
3 0
0 24
```
<!-- .element: style="font-size:48%" -->
Note:
行列は `*` で通常の行列積になりますっこれ便利っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### ブロードキャスト
```julia
julia> sin(0.1)
0.09983341664682815
julia> sin.([0.1, 0.2, 0.3, 0.4])
4-element Array{Float64,1}:
0.0998334
0.198669
0.29552
0.389418
julia> [0.1, 0.2, 0.3, 0.4] .^ 2
# => [0.01, 0.04, 0.09, 0.16]
```
<!-- .element: style="font-size:50%" -->
Note:
関数名と `(` の間に `.` を置くと、普通の関数を配列に拡張してくれる(ブロードキャスト)っ
`.^` のように演算子の前に `.` を書いても同様(先ほど出た `.+` `.*` もブロードキャスト)っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 関数定義
```julia
julia> f(x) = x^2 + 2x - 1
f (generic function with 1 method)
julia> f(1)
2
julia> f.(1:5)
# => [2, 7, 14, 23, 34]
```
Note:
数学のように直感的な記述で関数を定義可能っ
`2x` は `2*x` の省略形、曖昧さがなければリテラルと他の識別子が続く場合などに勝手に乗算と解釈してくれるっ
またユーザ定義関数も `.` をつけて自動的にブロードキャスト対応っ
----
<!-- .slide: data-background-color="rgba(213,99,92,0.3)" -->
### 有理数・複素数
```julia
julia> 1//2 == 0.5
true
julia> 1//2 - 1//3
1//6
julia> 1im ^ 2 == -1
true
julia> (1.0 + 0.5im) * (2.0 - 3.0im)
3.5 - 2.0im
```
Note:
有理数・複素数を標準サポート。
`//` は有理数除算(結果は有理数)
`im` は虚数単位。
どちらも四則演算も普通に書けますっ
---
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
# 多重ディスパッチ<br><small>とは?<!-- .element: style="font-size:75%" --></small>
<!-- .element: style="font-size:300%" -->
Note:
こっからが今日の本題っ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
## 多重ディスパッチ
> 多重ディスパッチ(英: Multiple dispatch)またはマルチメソッド(英: Multimethods)は、多重定義された関数やメソッドなどについて、そこで呼び出されるべき1つの定義を選出し実行する(ディスパッチする)際に、2個以上の複数の引数が関与してどれかひとつを選ぶこと(特殊化)がおこなわれるものである。
<!-- .element: style="font-size:71%" -->
(出典: [Wikipedia: 多重ディスパッチ](https://ja.wikipedia.org/wiki/%E5%A4%9A%E9%87%8D%E3%83%87%E3%82%A3%E3%82%B9%E3%83%91%E3%83%83%E3%83%81))
<!-- .element: style="font-size:50%" -->
Note:
っ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### つまり…
+ 関数を多重定義する
+ **実行時に** どれを実行するか決まる
+ ↑ここがポイント
<!-- .element: style="font-size:144%" -->
Note:
っ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
## Julia での使用例
+ 各種演算子(`+`/`-`/`*`/`/`/`\`/`÷`/…)
+ IO関連(`show()`/`print()`/`write()`/…)
+ その他ほとんどの関数
Note:
一部の演算子(`=`/`&&`/`||`)、ビルトイン関数以外は全て多重ディスパッチ対象っ
---
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
## コード例(1)
Note:
実際に体感してみましょうっ
ここの例は [ThinkJulia.jl](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html) の [Exercise 17-3](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html#_exercise_17_3) をベースにしていますっ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### `Struct Point`
```julia=
struct Point
x
y
end
p1 = Point(1.0, 2.0)
p2 = Point(3.0, 4.0)
```
----
### `p1 + p2`
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
```julia=9
import Base.+ # おまじない
function +(p1::Point, p2::Point)
Point(p1.x + p2.x, p1.y + p2.y)
end
p1 + p2
# => Point(4.0, 6.0)
```
Note:
`+` 演算子の多重定義(オーバーロード)をしていますっ
すでにシステムで定義されている演算子(関数)なので、このように `import Base.+` を予め記述するか、`function Base.:+(〜)` と書く必要があります。
----
### `p1 + (2.5, 3.2)`
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
```julia=9
function +(p::Point, t::Tuple)
Point(p.x + t[1], p.y + t[2])
end
p1 + (2.5, 3.2)
# => Point(3.5, 5.2)
```
Note:
ここでは簡単のため、第2引数を `Tuple` とだけ指定していますが、実際には `NTuple{2}` のように要素数を特定したり、さらに `NTuple{2,Number}` のように型を特定した方が良いでしょうっ
----
### `(2.5, 3.2) + p2`
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
```julia=9
function +(t::Tuple, p::Point)
# TODO: 実装してみましょう!
end
(2.5, 3.2) + p2
# => Point(5.5, 7.2)
```
Note:
いくつか方法がありますよっ
----
### Point
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
+ 引数に **型アノテーション** を付ける
+ 関数の実装を書き分ける
Note:
Juliaの演算子オーバーロードは、実は多重ディスパッチのおかげっ!
---
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
## コード例(2)
Note:
もう少し複雑な例っ
ここの例も [ThinkJulia.jl](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html) の [17. Multiple Dispatch](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html#chap17) をベースにしていますっ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### `abstract type AbstractTime`
<div>and some function declarations…</div><!-- .element: style="text-align: left" -->
```julia=
abstract type AbstractTime end
function gethour end
function getminute end
function getsecond end
```
Note:
引数列なし(`()` さえもなし)で記述した関数定義は所謂『関数宣言』のような役割をしますっ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### `show`
```julia=7
using Printf
function Base.show(io::IO, time::AbstractTime)
@printf(io, "%02d:%02d:%02d",
gethour(time),
getminute(time),
getsecond(time))
end
```
Note:
`Base.show()` を多重定義すると、REPL でインスタンスを参照したときなどにその情報が表示されます。
他言語の `.toString()` とか `.__str__()` に類似(同一ではない)
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### `struct MyTime`
<div>and some method implementations…</div><!-- .element: style="text-align: left" -->
```julia=16
struct MyTime <: AbstractTime
hour::Integer
minute::Integer
second::Integer
end
gethour(time::MyTime) = time.hour
getminute(time::MyTime) = time.minute
getsecond(time::MyTime) = time.second
```
Note:
`《関数名》(引数列) = 《式》` と言う書式でも関数定義が出来ます。
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
#### `MyTime(12, 34, 56)`
```julia=26
MyTime(12, 34, 56)
# => 12:34:56
```
Note:
`MyTime` 型で `show()` を多重定義していませんが、その supertype である `AbstractTime` 型では定義されているので、そちらが呼ばれましたっ
後その中で参照されている `getxxxx(time)` は、新しく定義した関数が呼ばれていますっ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### `struct MyTime2`
<div>and some method implementations…</div><!-- .element: style="text-align: left" -->
```julia=29
struct MyTime2 <: AbstractTime
seconds::Integer
end
gethour(time::MyTime2) = time.seconds ÷ 3600
getminute(time::MyTime2) = time.seconds ÷ 60 % 60
getsecond(time::MyTime2) = time.seconds % 60
```
Note:
`MyTime2` 型は、時刻として午前0時からの秒数だけを保持する型。
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
#### `MyTime2(10000)`
```julia=37
MyTime2(10000) # 午前0時の10000秒後は 2:46:40
# => 02:46:40
```
Note:
`MyTime2` 型も普通に `show()` できているのは先ほどと同じ理由っ
その中で参照されている `getxxxx(time)` も `MyTime2` 型に合った関数が呼ばれていますっ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### Point
+ 多重ディスパッチ設計 ≒ **インターフェース設計**
+ 型継承(subtyping)を理解すると多重ディスパッチがもっと面白くなる!
Note:
次回は型システムについて話したいですっ
----
<!-- .slide: data-background-color="rgba(96,173,81,0.3)" -->
### 演習
```julia=40
function Base.:+(time::AbstractTime, sec::Integer)
# TODO: 実装してみましょう!
end
# 必要なら他の関数も定義/多重定義してもOK!
MyTime1(12, 34, 56) + 7890
# => 14:46:26
MyTime2(10000) + 1234
# => 03:07:14
```
Note:
実装してみましょうっ
---
<!-- .slide: data-background-color="rgba(170,121,193,0.3)" -->
# まとめ
----
<!-- .slide: data-background-color="rgba(170,121,193,0.3)" -->
+ 多重ディスパッチこわくない!
+ 多重ディスパッチ使いこなせ!
+ Julia 楽しい!
Note:
っ
----
<!-- .slide: data-background-color="rgba(170,121,193,0.3)" -->
## 参考リンク
+ [Methods](https://docs.julialang.org/en/v1/manual/methods/) - [Julia Documentation](https://docs.julialang.org/en/v1)
+ [17. Multiple Dispatch](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html#chap17) - [ThinkJulia.jl](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html)
---
<!-- .slide: data-background-color="rgba(170,121,193,0.3)" -->
# おまけ
----
<!-- .slide: data-background-color="rgba(44,214,221,0.3)" -->
## 来栖川電算
Note:
スポンサー枠っ
----
<!-- .slide: data-background="https://i.imgur.com/5CbxlN7.jpg" data-background-color="rgba(44,214,221,0.3)" -->
Note:
![募集中!](https://i.imgur.com/5CbxlN7.jpg)
---
<!-- .slide: data-background-color="rgba(170,121,193,0.3)" -->
ご清聴ありがとうございます。
Note:
ご清聴ありがとうございますっ!
{"metaMigratedAt":"2023-06-14T21:37:35.160Z","metaMigratedFrom":"YAML","title":"多重ディスパッチ入門","breaks":"true","slideOptions":"{\"transition\":\"slide\",\"theme\":\"league\"}","contributors":"[{\"id\":\"80062a4b-8dad-49ac-95bf-848ce0686e9e\",\"add\":6773,\"del\":7168}]"}