Upgrade to Pro — share decks privately, control downloads, hide ads and more …

パターンマッチングについて_JSConf版.pdf

 パターンマッチングについて_JSConf版.pdf

ECMAScriptのStage 1仕様案として、パターンマッチングが検討されています。 動的言語ゆえに従来のJSでは書きづらかった「オブジェクトの厳密な定義」を宣言的にスマートに書ける、非常に強力で野心的ともいえる仕様です。 そのためか、かなりの難産になっていますが、採用されれば従来オブジェクト定義を担ってきたTypeScriptを含め、JavaScriptのエコシステムの変革が促進されることでしょう。

Avatar for NAGAYAMA Toshiaki

NAGAYAMA Toshiaki

November 16, 2025

Other Decks in Programming

Transcript

  1. Cautions English annotations are added to this slide. However due

    to the space limitation, not everything is annotated. I try to cut annotation where my intention are easily guessable. If my explanation is hard to understand, this is my fault, not because the spec is difficult. I'm sorry, speaking is Japanese only.
  2. アジェンダ? Agendas 混 沌 と し た JavaScript 界 隈

    に パ タ ー ン マ ッ チ ン グ が ! ,-'"ヽ / i、 / ̄ ̄ ヽ, _/\/\/\/|_ { ノ "' ゝ / ', \ / / "' ゝノ {0} /¨`ヽ{0} < is式 > / ヽ._.ノ ', / \ i `ー'′ '.  ̄|/\/\/\/ ̄ / match句 }. i' /、 ,i.. い _/ `-、.,, 、_ i /' / _/ \`i " /゙ ./ (,,/ , ' _,,-'" i ヾi__,,,...--t'" ,| ,/ / \ ヽ、 i | (、,,/ 〉、 、,} | .i `` ` ! 、、\ !、_n_,〉> マッチャーパターン AAのネタ元は殺伐だったorz Keywords: • match clause • is expression • Matcher patterns
  3. 自己紹介 Self introduction • 永山俊明 Toshiaki NAGAYAMA • 株式会社サザビーリーグHR 横浜事業所所属

    oプログラマーとして働いています o もともと専門はC#だったが、JavaScript や TypeScript も使っています o ASD当事者。ADHDも持っているかも? o Qiita: @Nagachan_T、note: 永山俊明 • Works at SAZABY LEAGUE HR Inc. as an programmer oSpecialized in C#, but uses JavaScript and TypeScript in work o Has ASD, maybe ADHD?
  4. 自己紹介 Self introduction • 株式会社サザビーリーグHRとは o株式会社サザビーリーグの特例子会社 (発達障害に特化) ▪ 親会社は「Afternoon Tea」「Shake

    Shack」「CANADA GOOSE」などを運営している o開発のほか、情報管理やWeb製作などで本社に貢献 ▪ 事業所ごとにやっていることは違う • About SAZABY LEAGUE HR Inc. o A subsidiary of SAZABY LEAGUE Inc. ▪ The Agency company of Shake Shack, CANADA GOOSE, etc. in Japan o Most of our workers have developmental disorder o We develop software, manage information, building web pages and so on ▪ Each office has its own professions
  5. Pattern Matchingとは何だろうか What is Pattern Matching? • 引数オブジェクトのチェックをするための構文 Checking the

    given object argument o 所定の型か Which type? ▪ 例えば数値であるかどうか Is it a number? o 所定の値か Is it the exact value? ▪ 例えば42であるかどうか Is it 42? o所定のプロパティを持っているか Does it have specific properties? ▪ 例えばobject型で、fooというプロパティがあるかどうか Is it an object which has property foo?
  6. C# のパターンマッチング例 Pattern Matching in C# public static void TestAnObject(object

    tested) { switch(tested) { case int i when i == 42: // testedの値が42である。 Console.WriteLine("42TH ZONE! BLACK HOLE!"); break; case int _: // testedの型が42以外のint(整数)である。 // 値を使わないので「_」で破棄する。 Console.WriteLine("You Inputted an integer."); break; case string s when s.Length <= 5: // testedの型が5文字以下のstring(文字列)である。 Console.WriteLine("You Inputted a short string."); break; case string _: // testedの型が(6文字以上の)stringである。 // 値を使わないので「_」で破棄する。 Console.WriteLine("You Inputted a long string."); break; default: Console.WriteLine("What did you input to me?"); break; } // 右に続く string something = tested switch // 右辺として使える switch文 { // ラムダ式(JSで言うアロー関数)の右側の値を返す int i when i <= 5 => "very few", // 「<=」は矢印じゃない int i => "enough", string s => s, _ => "nothing meaningful" // defaultに相当 }; } Javaも似たような実装となっているが、 JavaScript では switch 式の拡充としないことにした。 JSの場合既存の文法を触るのは怖い。 In JavaScript, the community decided to make a new term, instead of extending switch
  7. Pattern Matchingとは何だろうか What is Pattern Matching? • すでにJava、C#、Rubyなどに実装済み • ECMAScriptでも仕様が検討されている

    oTC39ではStage 1、まだまだ先は長い ▪ Stage 1になって6年以上経っている ▪ このプレゼンがステージを進める力となれば幸いである • OOP languages such as Java, C#, Ruby has pattern matching • Currently, the specifications for ECMAScript has been developing o Stage 1 at TC39 for 6 years oHope this presentation can push this spec going foreward
  8. パターンマッチングがあると何が嬉しいの? 1. オブジェクトの検証が楽になる! 自由に書ける! Easy to Validate • 今書こうとすると面倒だよね 2.

    検証後の返り値を簡単に返せる! Easy to get return values • 不安定なletを使う理由が少なくなる You can reduce instable lets 3. 検証のついでに変数を初期化(束縛)できる! Initialize(bind) values • 後述のisによる検証で威力を発揮する Will be neat at is expression 4. 型堅牢性の向上が期待できる Enhances type robustness • TypeScriptにどれほど影響があるかは未知数 Not sure how much this spec affects TypeScript
  9. ものすごい端折った書式 Concise syntax • match (検査対象) { when <パターンA>:<返り値の式>; when

    <パターンB>:<返り値の式>; … default: <いずれのパターンとも合わない場合の返り値の式>; } o式が複数行になる場合はdo式を用いる(文を認めると面倒くさい) Rather stick to do expressions than accepting statements • <検査対象> is <パターン> o If文などに簡単に組み込めるパターンマッチング Pattern matching for if statements o is の代わりに ~= 記号も考えられている "~=" might substitute is
  10. do expressions • 複数行にわたる文を式として処理するための文法案 (stage 1) A proposal syntax for

    managing multiple statements into single expression • do { 文; 文; } と書き、最後の文の実行結果を値として返す Returns ther result of the last expression inside curly braces • do expressions 案が廃案になった場合、pattern matching が巻き 取って仕様の一部にすることが検討されている When do expressions proposal is dismissed, do { } would be inside the specs of Pattern Matching
  11. Matcher Patterns • 分解パターンにインスパイアされたドメイン固有言語 The DSL for pattern matching inspired

    by deconstruction pattern • 現在固まっている構文は以下 1. 値パターン (Value patterns) ▪ 文字列が"foo"であるなどのチェック 2. 構造パターン (Structure patterns) ▪ 配列パターン Array patterns ▪ オブジェクトパターン Object patterns ▪ 展開パターン Extractor patterns ▪ 引数パターン Arglist patterns 3. 結合パターン (Combinator patterns) ▪ 上記をand、orでつなげる ▪ notで条件を否定できる 'not' nagates conditions 4. ガードパターン (Guard Patterns) ▪ If () のカッコの中では通常のJSが書けるがマッチはしない You can write normal JS inside the parenthesis after if. This is not a pattern
  12. 構造パターンの例 Structure patterns • Array patterns ["foo", {bar}] • Object

    Patterns {foo, let bar, baz: "qux", hoge: {piyo: Number}} • Extractor Patterns anObject.foo.bar ← barは関数! • Arglist patterns foo(bar, const baz, ...) • 後日チートシートをQiitaに上げます (約束)
  13. [Symbol.customMatcher]関数 (function) • 特殊なオブジェクトに対してマッチ条件を設定できる You can tell pattern matching to

    use custom match condition for specific object • class の static method として[Symbol.customMatcher]を定義した り、既存 object なら prototype 拡張を行う • オブジェクトのフォーマットを確認する関数であり、 等値判定をするための機構ではない! This feature is not for validating equality o Map や Set の等値判定には使われない Not intended to use inside the keys for Map and Set
  14. Reactのreducerを パターンマッチングにすると… export function reducer(state, action) { switch (action.type) {

    case "setHeight": { return setState(action.height / 100, state.weight); } case "setWeight": { return setState(state.height, action.weight); } case "clearAll": { return { height: 0, weight: 0, idealWeight: 0, bmiIndex: 0, }; } } } export function reducer(state, action) { return match(action) { when {const height: Number}: setState(height / 100, state.weight); when {const weight: Number}: setState(state.height, weight); default: { height: 0, weight: 0, idealWeight: 0, bmiIndex: 0, }; } } } 身体測定データ管理アプリの例 for body measurements app
  15. Jsonのパース例 Parsing Json const json = { "unitName": "Happy Around!",

    "members": [["愛本りんく", "vocal"], ["明石真秀", "DJ"], ["大鳴門むに", "VJ"], ["渡月麗", "Keyboard"]], } let unitName, dj; if ("unitName" in json && typeof json.unitName === "string") { unitName = json.unitName; } if ("members" in json) { const {members} = json; if (Array.isArray(members)) { dj = members.find(member => Array.isArray(member) && typeof member[0] === "string" && member[1] === "DJ")?.[0]; } } if (unitName !== undefined && dj !== undefined) { console.log(`${unitName}のDJは${dj}です。`); // 「Happy Around!のDJは明石真秀です。」 } Trying to extract the unit name and DJ's name safely
  16. Jsonのパース例 Parsing Json const json = { "unitName": "Happy Around!",

    "members": [["愛本りんく", "vocal"], ["明石真秀", "DJ"], ["大鳴門むに", "VJ"], ["渡月麗", "Keyboard"]], } if (json is { const unitName, members: [...const members: [String, String]]}) { const [dj] = members.find(member => member is [, "DJ"]); if (dj !== undefined) { console.log(`${unitName}のDJは${dj}です。`); } } パターンマッチングなら! With pattern matching 仕様がまだ固まりきっていないので雰囲気を知ってほしい あえて言おう、「細けえことは気にするな!」と Specs may change soon. Just know how to write the pattern matcing
  17. 補足 Complement • Jsonのパース例について o members.some(member => member is [String

    and const dj, "DJ"]) として も dj の束縛が外に出ない o スコープが some の括弧内に閉じ込められてしまう Scope is inside parenthesis of some decrelation • そもそもDJが2人いたら何が引っ掛かるか予測できない When there are 2 DJs, you cannot guess what is picked up o そのため、配列の中身を順次スキャニングするには向いていない Pattern Matching is not suitable for scanning inside arrays • おそらくこの対応はコストがかかるし難しいと思われる Managing this problem is a difficult task that needs some cost
  18. 個人的にパターンマッチングに望むこと What I hope to Pattern Matching • TypeScriptとの連携 Combination

    with TypeScript o複雑なオブジェクトの判別をつけるのは現状難しい Detecting Complex objects is currently a tough task ▪ TSは事前に呼び出す関数の型定義をチェックするだけなので、 ユーザー定義型ガードが無いと本当の意味で安心できない We cannot assure what is inside the object without user defined type guards because TS only checks types before compiling ▪ パターンマッチングはその問題をエレガントに解決しうる Pattern matching will solve this problem elegantly!
  19. 個人的にパターンマッチングに望むこと What I hope to Pattern Matching • TypeScriptとの連携 o型定義からパターンマッチングを生成できると助かる

    Generating pattern matching from type definition must be useful ▪ TSでしか意味がなかった型定義がバニラJSでも生きる! Type definitions are now helpful inside vanilla JS ▪ TS⇔JS間でのコードの行き来が捗る Interops between TS and JS are better than ever o逆にパターンマッチングの結果と型定義が紐づくとすごいありがたい Pattern matching would bear type definitions o どちらにせよTS陣営の目立った動きはまだない TypeScript GitHub does not have many issues about Pattern matching ▪ ごくごくたまに議論の俎上に上がる程度
  20. 個人的にパターンマッチングに望むこと What I hope to Pattern Matching • まだ仕様がはっきりしないパターンがあるので煮詰まって欲しい Spec

    is still under construction, so some patterns are not made well o 展開パターンは資料自体が曖昧だし、名前も分かりづらい Extractor patterns are not well documented, and name is hard to know o 野心的だがポテンシャルはすごい高いのでご期待ください I think this spec is very ambitious, but this will change how to write JS forever. It's such a big spec!
  21. ご清聴ありがとうございました • 詳しくは拙稿を読んでください oECMAScriptのPattern Matching 案について ▪ https://qiita.com/Nagachan_T/items/ef7af6128b597adb54ee • この案のGitHubにたまに質問したりしています!

    I sometimes ask the team about the spec • この案が正式化するには皆さんの声が必要です! This spec needs your attention! o こんな面白い仕様案があるんだと広めていただけるとありがたいです Please share it!