---
title: Tackling Side Effects with Functional Programming and Flix: JVM関数型言語Flixで学ぶ副作用の分離/局所化戦略
tags:  #関数型プログラミング #関数型言語 #flix  
author: [Kent OHASHI](https://image.docswell.com/user/lagenorhynque)
site: [Docswell](https://www.docswell.com/)
thumbnail: https://bcdn.docswell.com/page/L71R3PV27G.jpg?width=480
description: JVMで動作する静的型付き関数型言語Flix ( https://flix.dev/ )のコード例とともに、関数型プログラミングの世界でよく知られている副作用の分離/局所化の手法に親しもう。  JJUG CCC 2026 Fallセッション概要: https://sessionize.com/s/lagenorhynque/tackling-side-effects-with-functional-programming-/187715
published: November 28, 26
canonical: https://image.docswell.com/s/lagenorhynque/K6NR2X-tackling-side-effects-with-functional-programming-and-flix
---
# Page. 1

![Page Image](https://bcdn.docswell.com/page/L71R3PV27G.jpg)

Tackling Side Effects
with Functional Programming
and Flix
関数型言語Flixで学ぶ副作用の分離/局所化戦略
JVM
#jjug_ccc #jjug_ccc_i
1


# Page. 2

![Page Image](https://bcdn.docswell.com/page/G7W1P2L2J2.jpg)

🐬カマイルカ
lagénorhynque
関数型プログラミング(言語)の愛好者/実践者
特にClojure, Haskell, Flixがエレガントで好き
関数型まつりの運営スタッフ(座長のひとり)
株式会社スマートラウンドのシニアエンジニア
スタートアップと投資家のやり取りを効率化する
データ管理プラットフォームを開発
Java, Scala, Clojure, KotlinとJVM言語での開発実務
に長く取り組んできた
2


# Page. 3

![Page Image](https://bcdn.docswell.com/page/4JZPKDM473.jpg)

今回のテーマ
JVMで動作する静的型付き関数型言語
Flixのコード例とともに、関数型プロ
グラミングの世界でよく知られてい
る副作用の分離/局所化の手法を分か
りやすく解説する。
3


# Page. 4

![Page Image](https://bcdn.docswell.com/page/YE6MQ1NGJV.jpg)

きっかけ: 関数型まつり2026での🐬の発表
速習FP in Scala with Flix: Flix言語で親しむ純粋関数型のコード設計
4


# Page. 5

![Page Image](https://bcdn.docswell.com/page/GE5ZR45X74.jpg)

書籍Functional Programming in Scalaをベースに
(純粋)関数型プログラミングの典型手法を概観した
→ 関数型プログラミングとは、副作用の回避に
始まり、副作用の扱い方に向き合うスタイル
関連してDomain Modeling Made Functional:
Tackle Software Complexity with Domain-Driven
Design and F#
(
訳書: 『関数型ドメインモデリング ドメイン駆動設計とF#でソフトウェアの複雑さに立ち向かおう』)
→ ソフトウェアの複雑性(complexity)の中で特に
副作用(side effects)との向き合い方について関数
型プログラミングの観点から掘り下げてみる
5


# Page. 6

![Page Image](https://bcdn.docswell.com/page/972RDVNQER.jpg)

話すこと
副作用の扱い方を議論する上で必要な範囲での関数
型プログラミング一般とFlix言語の基礎解説
副作用の分離/局所化に関わる典型的な手法
話さないこと
Flix言語の特徴や機能の網羅的な解説
副作用の分離/局所化に関わるあらゆる手法の紹介
6


# Page. 7

![Page Image](https://bcdn.docswell.com/page/DJYD23PYJM.jpg)

副作用とは何か、なぜ重要か
言語の基本
関数型プログラミングの道具箱
副作用の分離/局所化のアプローチ
1.
2. Flix
3.
4.
7


# Page. 8

![Page Image](https://bcdn.docswell.com/page/V7N68V5R78.jpg)

1.
副作用とは何か、なぜ重要か
8


# Page. 9

![Page Image](https://bcdn.docswell.com/page/YJ9LK6YZE3.jpg)

関数型プログラミングの文脈での「副作用」
Domain Modeling Made Functional 第3章終盤では
A major aim of functional programming is to
work with functions that are predictable and
easy to reason about without having to look
inside them. In order to do this, we will try to
work with immutable data wherever possible
and try to ensure that our functions have
explicit dependencies instead of hidden
dependencies. Most importantly, we will try to
avoid side effects in our functions, including
randomness, mutation of variables outside the
function, and most importantly, any kind of
I/O.
9


# Page. 10

![Page Image](https://bcdn.docswell.com/page/GJ8XRZKY7D.jpg)

内部実装を読むまでもなく)予測可能で推論しやす
い関数を扱うのが関数型プログラミングの主な目的
そのために:
可能な限り不変データを扱う
関数は明示的な依存を持つようにする
副作用(ランダム性、関数外の変数の書き換え、
任意のI/O)を避ける
🐬&lt; よく知られているカジュアルな説明という印象
(
10


# Page. 11

![Page Image](https://bcdn.docswell.com/page/LJL8KDZ9ER.jpg)

Functional Programming in Scala
第1章冒頭では
A function has a side effect if it does something
other than simply return a result. This includes,
for example, the following cases:
Modifying a variable
Modifying a data structure in place
Setting a field on an object
Throwing an exception or halting with an
error
Printing to the console or reading user input
Reading from or writing to a file
Drawing on the screen
11


# Page. 12

![Page Image](https://bcdn.docswell.com/page/47M62PVVJW.jpg)

単に戻り値を返す以外のことをする関数には副作用
がある
副作用には例えば以下が含まれる:
変数を更新する
データ構造を置き換えて(破壊的に)更新する
オブジェクトのフィールドを設定する
例外をスローしたりエラーで停止したり
コンソールに印字したりユーザー入力を読んだり
ファイルを読み書きする
画面に描画する
12


# Page. 13

![Page Image](https://bcdn.docswell.com/page/P7RPM12WJ9.jpg)

同書第1章中盤では
A function f with input type A and output type B
(...) is a computation that relates every value a
of type A to exactly one value b of type B such
that b is determined solely by the value of a.
Any changing state of an internal or external
process is irrelevant to computing the result
f(a). ... In other words, a function has no
observable effect on the execution of the
program aside from computing a result given
its inputs; we say that it has no side effects.
13


# Page. 14

![Page Image](https://bcdn.docswell.com/page/PJX3VYDV7X.jpg)

入力型 A 、出力型 B の関数 f とは、型 A のあらゆ
る値 a をそれぞれ型 B のちょうど1つの(a の値のみ
によって定まる)値 b に対応付ける計算
内外のプロセスの任意の状態変更は f(a) の結果
の計算とは無関係
関数がプログラムの実行において入力から結果を
計算する以外に観測可能な作用がないとき、関数に
副作用がないという
このあと、参照透過性という概念を用いたより厳密な
解説が続く。
14


# Page. 15

![Page Image](https://bcdn.docswell.com/page/3JKYQ3X57D.jpg)

同書第14章終盤では
An expression e is referentially transparent
with regard to a program p if every occurrence
of e in p can be replaced by the result of
evaluating e without affecting the meaning of
p.
... tracking effects is a choice we make as
programmers. It’s a value judgement, and there
are trade-offs associated with what we choose.
15


# Page. 16

![Page Image](https://bcdn.docswell.com/page/LE39PG51E5.jpg)

式 e は、プログラム p に現われるすべての e を e
の評価結果で置き換えても p の意味に影響を与え
ないとき、 p について参照透過
作用を追跡するかどうかはプログラマが行う選択で
あり、価値判断であり、トレードオフを伴う
🐬&lt; 式が参照透過であり、関数が純粋である(副作用
を持たない)ことは絶対的ではなく観測者に依存する
相対的なもの
16


# Page. 17

![Page Image](https://bcdn.docswell.com/page/8EDGL1DKEG.jpg)

関数型プログラミングの根幹に関わる副作用
副作用を回避するプログラミングスタイル(?)
純粋関数と不変データでプログラミングする
純粋な世界ではいろいろな問題が簡単になる 😆
推論も検証も合成も並列/並行処理も
ただし、副作用をもれなく回避できたとしたら、
外形的には何も起こらないdead code 😇
副作用を認識し制御するプログラミングスタイル
副作用を意識的に扱う(暗黙的に紛れ込ませない)
副作用を分離/局所化する(無秩序に拡散させない)
17


# Page. 18

![Page Image](https://bcdn.docswell.com/page/V7P32QX3J8.jpg)

言語の基本
2. Flix
18


# Page. 19

![Page Image](https://bcdn.docswell.com/page/2JV4D5LN7Q.jpg)

とは
エフェクトシステムの組み込みサポートが特徴的な
静的型付き関数型言語
副作用を伴う関数には IO エフェクトが付く
Scalaと関係が深いが非オブジェクト指向言語
(サブタイピング(部分型)/継承とも無縁)
JVM言語(Scala, Kotlin, Clojureなどと同じ)
主にHaskell, Scala, OCaml, Rustの影響が見られる
処理系の実装言語もScala
🐬&lt; 大雑把には「Scalaの皮を被ったHaskell」🐑
Flix
19


# Page. 20

![Page Image](https://bcdn.docswell.com/page/5EG1Y6X5JL.jpg)

コードの書き方(0): 事前準備
mkdir first-flix-project
cd first-flix-project
#
flix init
#
echo &#039;pub mod FirstFlixProject {}&#039; &gt; src/FirstFlixProject.flix
プロジェクトを生成
プロジェクトルートのモジュールファイルを追加
flix
コマンドでプロジェクトを生成する
20


# Page. 21

![Page Image](https://bcdn.docswell.com/page/4JQDM48L7P.jpg)

コードの書き方(1): モジュールとそのトップレベル関数
// src/FirstFlixProject/SimpleMath.flix
pub mod FirstFlixProject.SimpleMath {
//
pub def square(n: Int32): Int32 =
n * n
パブリック関数
プライベート関数
⚠️ 未使用のままだとコンパイルエラー
//
//
def double(n: Int32): Int32 =
n * 2
}
21


# Page. 22

![Page Image](https://bcdn.docswell.com/page/K74ZVQ25E1.jpg)

コードの書き方(2): トップレベル関数による定数
// src/FirstFlixProject/SomeModule.flix
pub mod FirstFlixProject.SomeModule {
//
0
pub def a(): Int32 = 1
パブリックな 引数関数
プライベートな 引数関数
⚠️ 未使用のままだとコンパイルエラー
//
0
//
def b(): Int32 = 2
}
トップレベル変数は存在しない
22


# Page. 23

![Page Image](https://bcdn.docswell.com/page/LJ1R3PM2JG.jpg)

コードの書き方(3): モジュールの利用
flix&gt; use FirstFlixProject.{SimpleMath =&gt; M}; \
&gt;
M.square(3)
9
flix&gt; use FirstFlixProject.{SimpleMath =&gt; M}; \
&gt;
List.map(M.square, List.range(0, 11))
0 :: 1 :: 4 :: 9 :: 16 :: 25 :: 36 :: 49 :: 64 :: 81 :: 100
:: Nil
flix&gt; use FirstFlixProject.{SimpleMath =&gt; M}; \
&gt;
List.range(0, 11) |&gt; List.map(M.square)
0 :: 1 :: 4 :: 9 :: 16 :: 25 :: 36 :: 49 :: 64 :: 81 :: 100
:: Nil
は式の区切り文字
は での行継続
はパイプ(ライン)演算子
;
\ REPL
|&gt;
23


# Page. 24

![Page Image](https://bcdn.docswell.com/page/GJW1P232E2.jpg)

コードの書き方(4): ローカル束縛
flix&gt; \\
&gt; use FirstFlixProject.{SimpleMath =&gt; M};
&gt; let x = 5;
&gt; let y = M.square(x);
&gt; &quot;square(${x}) = ${y}&quot;
&gt; \\
square(5) = 25
\\
はREPLでの複数行入力の開始/終了
24


# Page. 25

![Page Image](https://bcdn.docswell.com/page/4EZPKDV4J3.jpg)

コードの書き方(5): 無名関数(ラムダ式)
flix&gt; (n -&gt; n * n * n)(2)
8
flix&gt; List.map(n -&gt; n * n * n, List.range(0, 11))
0 :: 1 :: 8 :: 27 :: 64 :: 125 :: 216 :: 343 :: 512 :: 729 ::
1000 :: Nil
25


# Page. 26

![Page Image](https://bcdn.docswell.com/page/Y76MQ15GEV.jpg)

3.
関数型プログラミングの道具箱
26


# Page. 27

![Page Image](https://bcdn.docswell.com/page/G75ZR4YXJ4.jpg)

参考: 🐬の「関数型プログラミング」コンセプトマップ
Idris
永続性
Elm
Gleam
(persistence)
可変性
Agda
(mutability)
合成可能性
Elixir
(composability)
不変性
Lean
破壊的更新
(immutability)
Erlang
Haskell
(mutation)
型 安全性
Coq (Rocq)
( )
((type) safety)
参照透過性
重視する
もの
⾔語
Clojure
(referential transparency)
(languages)
副作⽤
純粋性
(values)
同図像性
ML
宣⾔型プログラミング
Lisp
(declarative programming)
命令型プログラミング
OCaml
(side effect)
(purity)
(homoiconicity)
F#
⼊出⼒
(imperative programming)
式指向
マクロ
(I/O)
(expression-oriented)
⽂指向
(macro)
パーサーコンビネーター
Standard ML
(statement-oriented)
(parser combinator)
Scala
抽象構⽂⽊
(abstract syntax tree; AST)
プロパティベーステスト
圏論
(property-based testing)
構⽂解析
離散数学
(category theory)
メタプログラミング
(parse)
(discrete mathematics)
(metaprogramming)
契約プログラミング
数学
形式⼿法
(contract programming)
関数型
プログラミング
(mathematics)
(formal methods)
理論
篩型
(reﬁnement type)
(theories)
型システム
意味論
(type system)
型推論
依存型
カリー=ハワード同型対応
(Curry–Howard
correspondence)
(multimethod)
継続
メモ化
アクターモデル
(actor model)
セルフホスティング
(self-hosting)
(protocol)
再帰
遅延評価
超循環評価器
(meta-circular evaluator)
プロトコル
アドホック多相
(ad hoc polymorphism)
(recursion)
(lazy evaluation)
(memoization)
ポリモーフィズム/多相
ジェネリクス
パラメータ多相
(polymorphism)
制御
評価
(trait)
変性
純粋関数型データ構造
(evaluation)
トレイト
(generics)
(parametric polymorphism)
(control)
(variance)
(purely functional
data structure)
遅延リスト/ストリーム
サブタイプ多相
(subtype polymorphism)
(lazy list/stream)
goroutines &amp; channels
CSP
(communicating sequential
processes)
並⾏プログラミング
パターン
(concurrent programming)
(patterns)
リスト
(vector)
永続データ構造
全域関数
(total function)
関数
(function)
⾼階関数
関数合成
(function composition)
ファンクター
クロージャー/関数閉包
データ
(data)
データ指向プログラミング
(data-oriented programming)
カリー化
メソッドチェーン
(method chaining)
pipes &amp; ﬁlters
オブジェクト
(destructuring)
再帰型
代数的データ型
(recursive type)
(algebraic data type; ADT)
(abstract data type)
(currying)
分配束縛
パターンマッチ
(pattern matching)
抽象データ型
部分適⽤
(partial application)
パイプ演算⼦
(pipe operator)
(monad)
(applicative)
(closure)
(higher-order function)
(inheritance)
モナド
アプリカティブ
(functor)
部分関数
継承
ベクター
(list)
(persistent data structure)
STM
(software transactional
memory)
(partial function)
(type class)
(continuation)
(call by need)
(apply)
(eval)
(overloading)
マルチメソッド
必要呼び
(type inference)
適⽤
評価
オーバーロード/多重定義
型クラス
末尾再帰
(semantics)
(tail recursion)
(dependent type)
(implementations)
(functional
programming)
ラムダ計算
(lambda calculus)
定理証明⽀援系
(theorem prover)
処理系/実装
直和型
直積型
(product type)
(sum type)
カプセル化
(encapsulation)
(object)
オブジェクト指向プログラミング
(object-oriented
programming)
デザインパターン
GoF
(GoF Design Patterns)
※
🐬 が思い浮かぶ概念/用語を連想的に列挙したもの(網羅的でも体系的でもない)
27


# Page. 28

![Page Image](https://bcdn.docswell.com/page/9J2RDVGQ7R.jpg)

型クラス
オーバーロード/多重定義
(type class)
(overloading)
マルチメソッド
末尾再帰
(multimethod)
(tail recursion)
継続
必要呼び
メモ化
(actor model)
再帰
遅延評価
(recursion)
(lazy evaluation)
ポリモーフィズム/多相
制御
ジェネリクス
パラメータ多相
(polymorphism)
トレイト
(generics)
(parametric polymorphism)
(control)
評価
(trait)
変性
純粋関数型データ構造
(evaluation)
(variance)
(purely functional
data structure)
遅延リスト/ストリーム
サブタイプ多相
(subtype polymorphism)
(lazy list/stream)
goroutines &amp; channels
CSP
(communicating sequential
processes)
並⾏プログラミング
パターン
(concurrent programming)
(patterns)
リスト
(vector)
永続データ構造
全域関数
(total function)
関数
(function)
(higher-order function)
関数合成
(function composition)
クロージャー/関数閉包
データ
(data)
データ指向プログラミング
カリー化
パイプ演算⼦
(currying)
メソッドチェーン
(method chaining)
pipes &amp; ﬁlters
オブジェクト
(destructuring)
(pattern matching)
再帰型
代数的データ型
(recursive type)
(algebraic data type; ADT)
(abstract data type)
(partial application)
分配束縛
パターンマッチ
抽象データ型
部分適⽤
(data-oriented programming)
(pipe operator)
モナド
(applicative)
ファンクター
(closure)
⾼階関数
(inheritance)
(monad)
アプリカティブ
(functor)
部分関数
継承
ベクター
(list)
(persistent data structure)
STM
(software transactional
memory)
(partial function)
(protocol)
(ad hoc polymorphism)
(memoization)
アクターモデル
プロトコル
アドホック多相
(continuation)
(call by need)
直和型
直積型
(product type)
(sum type)
カプセル化
(encapsulation)
(object)
オブジェクト指向プログラミング
(object-oriented
programming)
デザインパターン
GoF
(GoF Design Patterns)
28


# Page. 29

![Page Image](https://bcdn.docswell.com/page/DEYD23VYEM.jpg)

🐬が考える関数型プログラミングの基本ツール
関数とその組み合わせ/再利用
代数的データ型とパターンマッチング
再帰
高階関数
アドホック多相機構(型クラスなど)
29


# Page. 30

![Page Image](https://bcdn.docswell.com/page/VJN68VMRJ8.jpg)

関数とその組み合わせ/再利用
部分適用: 関数の引数を一部のみ適用すること
一部の引数を固定して別の関数と組み合わせる、
再利用する
乗算が定義された型 の
を受け取ってその積を返す関数
//
a x, y, z
flix&gt; def f(x: a, y: a, z: a): a with Mul[a] = x * y * z
Ok.
//
f
1
flix&gt; let f1 = y -&gt; z -&gt; f(2, y, z); \
&gt;
f1(3, 4)
24
//
f
2
flix&gt; let f2 = x -&gt; z -&gt; f(x, 3, z); \
&gt;
f2(2, 4)
24
//
f
1
2
flix&gt; let f3 = z -&gt; f(2, 3, z); \
&gt;
f3(4)
24
ラムダ式で包んで の第 引数に部分適用
ラムダ式で包んで の第 引数に部分適用
ラムダ式で包んで の第 、第 引数に部分適用
30


# Page. 31

![Page Image](https://bcdn.docswell.com/page/YE9LK6NZ73.jpg)

カリー化: 多引数関数を1引数関数の連鎖に変換す
ること
左から順に部分適用しやすくなる
カリー化を活かすには引数の順序の設計が重要
flix&gt; def f(x: a, y: a, z: a): a with Mul[a] = x * y * z
Ok. // f
: f = x -&gt; y -&gt; z -&gt; x * y * z
flix&gt; let f1 = f(2); \
// f
1
&gt;
f1(3, 4)
24
flix&gt; let f2 = f(2, 3); \ // f
1
2
&gt;
f2(4)
24
はすでにカリー化されている
の第 引数に部分適用
の第 、第 引数に部分適用
🐬&lt; 関数が常にカリー化される言語では部分適用の前
提として便利だが、そうでない言語で手動でカリー化
する意味はあまりない(直に部分適用すればよい)
31


# Page. 32

![Page Image](https://bcdn.docswell.com/page/GE8XRZNYJD.jpg)

関数合成(Flixでは &gt;&gt;): 複数の関数を繋ぐこと
e.g. f, g の順に適用する関数 h = f &gt;&gt; g
関連して、関数を連鎖的に適用する場合には
パイプ(ライン)演算子(Flixでは主に |&gt;)
flix&gt; \\
&gt; def sumOfEvens(upper: Int32): Int32 = // upper
&gt;
DelayList.startFrom(0) //
&gt;
|&gt; DelayList.filter(n -&gt; n `Int32.modulo` 2 == 0)
&gt;
|&gt; DelayList.takeWhile(n -&gt; n &lt;= upper)
&gt;
|&gt; DelayList.sum
&gt; \\
Ok.
flix&gt; sumOfEvens(100)
2550
自然数の無限リスト
までの偶数の和
では Function などの andThen, compose 、
もしくは任意のメソッドチェーンに相当
cf. Java
32


# Page. 33

![Page Image](https://bcdn.docswell.com/page/LEL8KDP97R.jpg)

代数的データ型とパターンマッチング
flix&gt; \\
&gt; //
&gt; enum Tree[a] { //
(
)
&gt;
case Leaf(a)
//
&gt;
case Branch(Tree[a], Tree[a]) //
&gt; }
代数的データ型の定義
ツリー 二分木
パターンマッチングによる分岐と分解
葉の場合(基底部)
枝の場合(再帰部)
&gt; //
&gt; def depth(t: Tree[a]): Int32 = match t { //
&gt;
case Tree.Leaf(_)
=&gt; 0 //
(
)
&gt;
case Tree.Branch(l, r) =&gt;
//
(
)
&gt;
1 + Int32.max(depth(l), depth(r))
&gt; }
&gt; \\
Ok.
flix&gt; use Tree.{Leaf, Branch}; \
&gt;
depth(Branch(Leaf(&#039;a&#039;), Branch(Leaf(&#039;b&#039;), Leaf(&#039;c&#039;))))
2
二分木の深さ
葉の場合 基底部
枝の場合 再帰部
ではsealed class/interfaceとswitch式に相当
cf. Java
33


# Page. 34

![Page Image](https://bcdn.docswell.com/page/4JM62P4VEW.jpg)

再帰
関数型言語でのプリミティブな繰り返しの手段
多くの関数型言語では末尾再帰形式の関数が
命令型のループ相当に最適化される
再帰的データ型((連結)リスト、ツリーなど)と
必然的に相性が良い
flix&gt; \\
&gt; def factorial(n: Int32): Int32 = // (
&gt;
@Tailrec //
&gt;
def go(x, acc) = //
&gt;
if (x &lt;= 0) acc
//
&gt;
else go(x - 1, x * acc); //
&gt;
go(n, 1)
&gt; \\
Ok.
flix&gt; List.map(factorial, List.range(0, 6))
1 :: 1 :: 2 :: 6 :: 24 :: 120 :: Nil
お馴染みの?)階乗関数
末尾再帰であることを保証するアノテーション
末尾再帰関数
基底部
再帰部
34


# Page. 35

![Page Image](https://bcdn.docswell.com/page/PJRPM1WWE9.jpg)

高階関数
関数を引数として受け取る、または戻り値として
返す関数
パターンを抽象化する汎用性の高いテクニック
述語関数
を受け取る関数
flix&gt; \\ //
pred
&gt; def sumOf(pred: Int32 -&gt; Bool, upper: Int32): Int32 =
&gt;
DelayList.startFrom(0)
&gt;
|&gt; DelayList.filter(pred)
&gt;
|&gt; DelayList.takeWhile(n -&gt; n &lt;= upper)
&gt;
|&gt; DelayList.sum
&gt; \\
Ok.
flix&gt; sumOf(n -&gt; n `Int32.modulo` 2 != 0, 100)
2500
🐬&lt; 例えば古典的なGoFのオブジェクト指向デザイン
パターンの多くは高階関数で簡潔に実装できる
35


# Page. 36

![Page Image](https://bcdn.docswell.com/page/PEX3VYPVJX.jpg)

アドホック多相機構(型クラスなど)
アドホック多相: パラメータ多相、サブタイプ多相
と並ぶポリモーフィズムの類型
オーバーロード(多重定義)も実現手法の一例
Flixではトレイト(= 型クラス)として利用できる
Javaでいう Object クラスのメソッドに
相当するものも型クラスとして定義される
e.g. Eq, Hash, ToString
Functor, Applicative, Monad なども
型クラスの典型例
36


# Page. 37

![Page Image](https://bcdn.docswell.com/page/3EKYQ3D5JD.jpg)

flix&gt; \\
&gt; //
:
&gt; trait HasSize[a] {
&gt;
pub def size(x: a): Int32
&gt; }
&gt; //
:
&gt; instance HasSize[String] { //
&gt;
pub def size(x: String): Int32 = String.length(x)
&gt; }
&gt; instance HasSize[List[a]] { //
&gt;
pub def size(x: List[a]): Int32 = List.size(x)
&gt; }
&gt; \\
Ok.
型クラスの定義 共通のインターフェース
型クラスのインスタンス 型ごとの実装
文字列の場合
リストの場合
flix&gt; HasSize.size(&quot;foo bar&quot;)
7
flix&gt; HasSize.size(List#{&#039;a&#039;, &#039;b&#039;, &#039;c&#039;})
3
37


# Page. 38

![Page Image](https://bcdn.docswell.com/page/L739PGR175.jpg)

4.
副作用の分離/局所化の
アプローチ
38


# Page. 39

![Page Image](https://bcdn.docswell.com/page/87DGL1YK7G.jpg)

種類のアプローチ
3
パラメータ化
副作用を持つ処理を引数で注入する
2. 処理のデータ化と解釈
副作用を持つ処理をデータで表して解釈に委ねる
3. 型レベルの分離/局所化
副作用を持つ処理を型でマークして閉じ込める
1.
39


# Page. 40

![Page Image](https://bcdn.docswell.com/page/VJP32Q63E8.jpg)

パラメータ化
副作用を持つ処理を引数で注入する
利用側から副作用を注入し、定義側は純粋
シンプルなDI手法としても機能する
副作用の分離/局所化の強制力はない(規律が求め
られる)
主な手段: 高階関数
ただの関数なのであらゆる言語で利用可能
4-1.
40


# Page. 41

![Page Image](https://bcdn.docswell.com/page/2EV4D53NJQ.jpg)

例題: カフェでクレジットカード決済でコーヒーを買う
コーヒーモジュール
値段を持つコーヒー型
コーヒー型の文字列表現
//
pub mod TacklingSideEffects.Coffee {
//
pub enum Coffee({price = Float64})
//
instance ToString[Coffee] {
pub def toString(coffee: Coffee): String =
let Coffee({price}) = coffee;
&quot;Coffee({price = ${price}})&quot;
}
//
pub def make(): Coffee =
Coffee({price = 2.0})
}
コーヒー型の値のファクトリー関数
flix&gt; use TacklingSideEffects.Coffee; \
&gt;
Coffee.make()
Coffee({price = 2.0})
41


# Page. 42

![Page Image](https://bcdn.docswell.com/page/57G1Y635EL.jpg)

高階関数による副作用の注入
クレジットカードモジュール
クレジットカードに値段の分だけ請求する関数 副作用あり
ℹ️
では副作用
を伴う関数に エフェクトが付く
ここでは簡単のため標準出力
//
pub mod TacklingSideEffects.HigherOrderFunction.CreditCard {
//
(
)
//
Flix
(I/O)
IO
pub def charge(price: Float64): Unit \ IO =
println(&quot;charging ${price}&quot;) //
}
カフェモジュール
//
pub mod TacklingSideEffects.HigherOrderFunction.Cafe {
use TacklingSideEffects.Coffee
//
(
)
//
ef
(
pub def buyCoffee(charge: Float64 -&gt; Unit \ ef):
Coffee \ ef =
let coffee = Coffee.make();
let Coffee.Coffee({price}) = coffee;
charge(price);
coffee
}
請求関数を受け取ってコーヒーを返す高階関数 純粋
ℹ️ は任意のエフェクトを表し、渡す関数で決まる エフェクト多相)
42


# Page. 43

![Page Image](https://bcdn.docswell.com/page/4EQDM45LJP.jpg)

利用例 クレジットカード決済でコーヒーを買う
//
1:
flix&gt; \\
&gt; use TacklingSideEffects.HigherOrderFunction.{Cafe,
CreditCard};
&gt; let cup = Cafe.buyCoffee(CreditCard.charge);
&gt; cup
&gt; \\
charging 2.0
//
(charge
)
Coffee({price = 2.0}) //
標準出力
評価結果
関数の副作用
利用例 決済なしでコーヒーを買う 無銭飲食 😈
//
2:
(
(?) )
flix&gt; \\
&gt; use TacklingSideEffects.HigherOrderFunction.Cafe;
&gt; let cup = Cafe.buyCoffee(_ -&gt; ()); //
&gt; cup
&gt; \\
Coffee({price = 2.0}) //
何もしない関数を渡す
評価結果
43


# Page. 44

![Page Image](https://bcdn.docswell.com/page/KJ4ZVQ9571.jpg)

処理のデータ化と解釈
副作用を持つ処理をデータで表して解釈に委ねる
利用側の解釈次第で副作用が生じ、定義側は純粋
値として自由に取り回し、実行と分離できる
副作用の分離/局所化の強制力はない(規律が求め
られる)
主な手段: 代数的データ型/型クラスによるDSLと
インタープリタ
ただのDSLと解釈なのであらゆる言語で利用可能
(表現の柔軟性や型レベルの制約は言語による)
4-2.
44


# Page. 45

![Page Image](https://bcdn.docswell.com/page/LE1R3PK2EG.jpg)

代数的データ型でのデータ化
請求モジュール
クレジットカードと金額の情報を持つ請求型
//
pub mod TacklingSideEffects.AlgebraicDataType.Charge {
//
pub enum Charge({
creditCard = CreditCard,
amount
= Float64
})
//
instance ToString[Charge] {
pub def toString(charge: Charge): String = ???
}
//
(
)
pub enum CreditCard(String) with Eq, ToString
請求型の文字列表現
文字列 識別名 を持つクレジットカード型
45


# Page. 46

![Page Image](https://bcdn.docswell.com/page/GEW1P2D272.jpg)

つの請求をまとめる関数
// 2
pub def combine(a: Charge, b: Charge):
Result[String, Charge] =
let Charge({creditCard = ccA, amount = amA}) = a;
let Charge({creditCard = ccB, amount = amB}) = b;
if (ccA == ccB) Ok(Charge({creditCard = ccA,
amount = amA + amB}))
else Err(&quot;Can&#039;t combine charges to different cards&quot;)
}
請求実行モジュール
//
pub mod TacklingSideEffects.AlgebraicDataType.ChargeExecutor {
use TacklingSideEffects.AlgebraicDataType.Charge
//
(
)
pub def execute(charge: Charge.Charge): Unit \ IO =
let Charge.Charge({creditCard, amount}) = charge;
println(&quot;charging ${amount} to ${creditCard}&quot;)
}
請求を解釈して実際に請求する関数 副作用あり
46


# Page. 47

![Page Image](https://bcdn.docswell.com/page/47ZPKDG4E3.jpg)

カフェモジュール
//
pub mod TacklingSideEffects.AlgebraicDataType.Cafe {
use TacklingSideEffects.AlgebraicDataType.Charge
use TacklingSideEffects.Coffee
//
(
)
pub def buyCoffee(cc: Charge.CreditCard):
(Coffee, Charge) =
let coffee = Coffee.make();
let Coffee.Coffee({price}) = coffee;
(coffee, Charge.Charge({creditCard = cc,
amount = price}))
コーヒーと請求のペアを返す関数 純粋
杯のコーヒーと請求のペアを返す関数 純粋
// n
(
)
pub def buyCoffees(cc: Charge.CreditCard, n: Int32):
Result[String, (List[Coffee], Charge)] =
let (coffees, charges) = buyCoffee(cc)
|&gt; List.repeat(n) |&gt; List.unzip;
charges
|&gt; Foldable.foldLeftM(Charge.combine,
Charge.Charge({creditCard = cc, amount = 0.0}))
|&gt; Functor.map(charge -&gt; (coffees, charge))
}
47


# Page. 48

![Page Image](https://bcdn.docswell.com/page/YJ6MQ1YG7V.jpg)

利用例 コーヒーを買うときのコーヒーと請求
//
1:
flix&gt; \\
&gt; use TacklingSideEffects.AlgebraicDataType.{Cafe, Charge};
&gt; Cafe.buyCoffee(Charge.CreditCard.CreditCard(&quot;A&quot;))
&gt; \\
(Coffee({price = 2.0}), Charge({creditCard =
CreditCard(A), amount = 2.0})) //
評価結果
利用例 コーヒーを 杯まとめて買うときのコーヒーリストと請求
//
2:
3
flix&gt; \\
&gt; use TacklingSideEffects.AlgebraicDataType.{Cafe, Charge};
&gt; Cafe.buyCoffees(Charge.CreditCard.CreditCard(&quot;A&quot;), 3)
&gt; \\
Ok((Coffee({price = 2.0}) :: Coffee({price = 2.0}) ::
Coffee({price = 2.0}) :: Nil, Charge({creditCard =
CreditCard(A), amount = 6.0}))) //
評価結果
48


# Page. 49

![Page Image](https://bcdn.docswell.com/page/GJ5ZR4GXE4.jpg)

利用例 クレジットカード決済でコーヒーを買う
//
3:
flix&gt; \\
&gt; use TacklingSideEffects.AlgebraicDataType.{Cafe, Charge,
ChargeExecutor};
&gt; let (cup, charge) =
Cafe.buyCoffee(Charge.CreditCard.CreditCard(&quot;A&quot;));
&gt; ChargeExecutor.execute(charge);
&gt; cup
&gt; \\
charging 2.0 to CreditCard(A) //
(execute
)
Coffee({price = 2.0})
//
標準出力
評価結果
関数の副作用
49


# Page. 50

![Page Image](https://bcdn.docswell.com/page/LE39PGR4E5.jpg)

型レベルの分離/局所化
副作用を持つ処理を型でマークして閉じ込める
利用側から注入/解釈することで、定義側で明示
した箇所でのみ副作用が生じる
コードの一部/全部に副作用がないことを静的に
保証できる
副作用の分離/局所化が型レベルで強制される
主な手段: モナド、エフェクト
型クラスや高カインド型、高ランク多相、
エフェクトシステムなどの言語機能が必要
4-3.
50


# Page. 51

![Page Image](https://bcdn.docswell.com/page/8EDGL1Y5EG.jpg)

エフェクトシステムとは
関数の作用(= エフェクト)を静的に追跡する仕組み
Flixでは言語組み込みで代数的エフェクトが提供
されている(Koka, OCamlなどと同様)
Haskell, Scalaなどではライブラリレベルで拡張
可能エフェクトとして実現するものもある
代数的エフェクトはJavaの検査例外の仕組みに
(部分的に)似ている
51


# Page. 52

![Page Image](https://bcdn.docswell.com/page/V7P32Q6DJ8.jpg)

の検査例外
Java
のメソッド
をスローしうる
// e.g. java.nio.file.Files
: IOException
public static String readString(Path path) throws IOException
をハンドリングしない
宣言に残る
をハンドリングする
宣言なし
// IOException
(throws
)
String readFile1(String filePath) throws IOException {
return Files.readString(Path.of(filePath));
}
// IOException
(throws
)
String readFile2(String filePath) {
try {
return Files.readString(Path.of(filePath));
} catch (IOException e) {
//
}
}
何らかのハンドリング
52


# Page. 53

![Page Image](https://bcdn.docswell.com/page/2JV4D53G7Q.jpg)

の代数的エフェクト
Flix
モジュールの関数
エフェクトを伴う
// e.g. Fs.FileRead
: FileRead
def read(f: String): Result[IoError, String] \ FileRead
エフェクトをハンドリングしない 関数のエフェクトに残る)
// FileRead
(
def readFile1(filePath: String):
Result[IoError, String] \ FileRead =
FileRead.read(filePath)
エフェクトをハンドリングする 関数のエフェクトなし
ℹ️ ハンドリング次第で別のエフェクトが加わることもある
// FileRead
(
)
//
def readFile2(filePath: String): Result[IoError, String] =
run {
FileRead.read(filePath)
} with /*
*/
何らかのハンドリング
53


# Page. 54

![Page Image](https://bcdn.docswell.com/page/5EG1Y6YDJL.jpg)

代数的エフェクトによる分離/局所化
決済モジュール
決済エフェクト
クレジットカードに指定金額を請求する関数
//
pub mod TacklingSideEffects.AlgebraicEffect.Payment {
//
pub eff Payment {
//
def charge(cc: CreditCard, amount: Float64): Unit
}
//
(
)
pub enum CreditCard(String) with Eq, ToString
文字列 識別名 を持つクレジットカード型
エフェクトをハンドリングして請求する関数 副作用あり
が外れて が加わる
// Payment
(
)
pub def runWithIO(f: Unit -&gt; a \ ef):
a \ (ef - Payment) + IO = // Payment
IO
run { f() } with handler Payment {
def charge(cc, amount, resume) = {
println(&quot;charging ${amount} to ${cc}&quot;);
resume() //
}
}
エフェクト発生地点から続く処理を再開
}
54


# Page. 55

![Page Image](https://bcdn.docswell.com/page/4JQDM4MX7P.jpg)

カフェモジュール
//
pub mod TacklingSideEffects.AlgebraicEffect.Cafe {
use TacklingSideEffects.AlgebraicEffect.Payment
use TacklingSideEffects.Coffee
//
(
)
//
pub def buyCoffee(cc: Payment.CreditCard):
Coffee \ Payment =
let coffee = Coffee.make();
let Coffee.Coffee({price}) = coffee;
Payment.charge(cc, price);
coffee
}
クレジットカードを受け取ってコーヒーを返す関数 純粋
ℹ️ 副作用が発生するかどうかはハンドリング次第
55


# Page. 56

![Page Image](https://bcdn.docswell.com/page/K74ZVQV2E1.jpg)

利用例 クレジットカード決済でコーヒーを買う
//
:
flix&gt; \\
&gt; use TacklingSideEffects.AlgebraicEffect.{Cafe, Payment};
&gt; let cup = run {
&gt;
Cafe.buyCoffee(Payment.CreditCard.CreditCard(&quot;A&quot;))
&gt; } with Payment.runWithIO;
&gt; cup
&gt; \\
charging 2.0 to CreditCard(A) //
(runWithIO
)
Coffee({price = 2.0})
//
標準出力
評価結果
関数の副作用
56


# Page. 57

![Page Image](https://bcdn.docswell.com/page/LJ1R3P3KJG.jpg)

種類のアプローチまとめ
パラメ 処理のデータ 型レベルの
ータ化 化と解釈
分離/局所化
手段 高階 代数的データ モナド、
関数 型、型クラス エフェクト
副作用 関数の データの解釈 モナド/エフェ
の所在 利用側 側
クトの実行側
強制力 なし なし
あり
言語の 制約 ほぼ制約なし 一部の関数型
選択 なし
言語のみ
3
57


# Page. 58

![Page Image](https://bcdn.docswell.com/page/GJW1P2PPE2.jpg)

おわりに: 副作用分離/局所化の基本戦略
🔭 明示的に扱うべき副作用は観測者次第で決まる
どこから見て純粋に保つか、どこで副作用を発生
させるか、どのように副作用を切り離すか
🧰 有力なアプローチの選択肢:
パラメータ化(高階関数)
処理のデータ化と解釈(代数的データ型/型クラス
DSLとインタープリタ)
型レベルの分離/局所化(モナド、エフェクト)
💡 関連キーワード: Freeモナド, tagless final, ST/IO
モナド, Flixのregion機構, 拡張可能エフェクト
58


# Page. 59

![Page Image](https://bcdn.docswell.com/page/4EZPKDK6J3.jpg)

Further Reading
Functional Programming in Scala, Second Edition
1
: Scala
第 版訳書 『 関数型デザイン＆プログラミ
ング』
fp-matsuri/fp-in-scala-exercises: FP in Scala ベ
ースの関数型プログラミング演習問題 by 関数型
まつり
lagenorhynque/fp-in-scala: Clojure/Flix実装 by
🐬
Domain Modeling Made Functional
訳書: 『関数型ドメインモデリング』
The Flix Programming Language: Flix公式サイト
59


# Page. 60

![Page Image](https://bcdn.docswell.com/page/Y76MQ1QLEV.jpg)

lagenorhynque/tackling-side-effects-withfunctional-programming-and-flix:
by
Clojurian
simple
JVM
Flix ——
: Flix
by
FP in Scala with Flix: Flix
:
2026
by
: Haskell, Scala, Clojure,
Elixir
:
2025
by
本セッションの
サンプルコード 🐬
が出会った
志向な 関数型言語
ファーストインプレッション 紹介記事
🐬
速習
言語で親しむ純粋関
数型のコード設計
関数型まつり セッション資料 🐬
関数型言語テイスティング
を比べて味わう関数型プログラミングの旨さ
関数型まつり セッション資料 🐬
60


