関数型プログラミング言語のエッセンスを感じる
2026-07-03
Webナイト宮崎 vol.22 〜てげ推し技術を語りたい〜
プロパティを一部だけ変更した「新しい値」を返す
type alias Model = { count: Int } countup : Model -> Model countup model = { model | count = model.count + 1 }
再代入や値を直接書き換えることもできない「不変性(immutable)」が言語レベルで制約になっている
最近同じような機能を持つ clone() の使い方が導入された
clone()
/* PHP 8.2 : readonly class */ readonly class Color { public function __construct( public int $red, public int $green, public int $blue, public int $alpha = 255, ) {} } clone($color, ['alpha' => 128]); /* プロパティを変えた新しい値を返す */
Shape 型の取りうるパターンを列挙
Shape
type Shape = Circle Float | Rectangle Float Float Circle 1.0 {- Shape型の値 -} Rectangle 210.0 294.0
pi : Float pi = 3.14159265358979323846264338327950288419716939937510 shapeArea : Shape -> Float shapeArea shape = case shape of Circle r -> pi * r * r Rectangle w h -> w * h
r, w, h などの変数に実際の値が束縛(binding)される
r
w
h
2023年のJava21アップデートで同じような機能が追加された
public sealed interface Shape permits Circle, Rectangle {} public record Circle(double radius) implements Shape {} public record Rectangle(double width, double height) implements Shape {}
(記述量はちょっと多いけど…)
switch 式(あるいは文)で変数への束縛ができる
switch
switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.width() * r.height(); }
case default
radius
if (shape instanceof Rectangle(double width, double height)) { return width * height; }
instanceof ではメンバー変数の束縛が使えるようになっている
instanceof
https://wiki.php.net/rfc/adts
PHPでもパターンマッチングなどを含む代数的データ型を実装すべきか、という議論は進められている
// Capturing values out of a pattern and binding them to variables if matched. $p is Point(x: 3, y: $y); // If $p->x === 3, bind $p->y to $y and return true. $assoc is ['a' => 'A', 'b' => $b]; // If $assoc['a'] === 'A', bind $assoc['b'] to $b and return true.
これまで変数への再代入やmutableなオブジェクトを中心としてきたプログラミング言語でも、不変なデータ定義や代数的データ型が選択肢として使えるようになる例は多くなってきている。
関数型プログラミング言語をちょっと学んでおくと「〇〇ゼミで見たやつだ!」となるかも。
ということで #miyazaki_fp いかがですか?
https://miyazaki-fp.connpass.com/
PHP 8.5: Clone With
PHP RFC: Algebraic Data Types
Java 21: シール・クラス
Java 21: パターン・マッチング