代æ°çããŒã¿åãšã¯ãåãšç©ãããªãããŒã¿åã§ãããåã¯éžæåŒãç©ã¯è¡šåœ¢åŒ
çŽç©ã»æ§é äœã»ã¿ãã«ã»ã¬ã³ãŒãã»ããŒãã«
çŽåãå
±çšäœãUNIONãããªã¢ã³ããåæ
Tagged unionïŒãŸãã¯discriminated union, variant, sum type, algebraic data typeãªã©ãšãåŒã°ããïŒã¯ãè€æ°ã®ç°ãªãåã®ããããäžã€ã®å€ãåãããšãã§ããããŒã¿æ§é ã§ããåå€ã¯ã¿ã°ïŒãŸãã¯ãã£ã¹ã¯ãªããã³ãïŒãšããŠç¥ãããç¹å®ã®åãšé¢é£ä»ããããŠããããã®ã¿ã°ã䜿çšããŠunionã®çŸåšã®åãèå¥ããããšãã§ããŸãã
以äžã¯ãTypeScriptã§ã®tagged unionã®äŸã§ãïŒ
type Shape =
{ kind: "circle"; radius: number }
| { kind: "square"; sideLength: number }
| { kind: "rectangle"; width: number; height: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.radius * s.radius;
case "square":
return s.sideLength * s.sideLength;
case "rectangle":
return s.width * s.height;
}
}
äžèšã®äŸã§ã¯ã`Shape`åã¯3ã€ã®ç°ãªã圢ç¶ãæã€ããšãã§ããããããã®åœ¢ç¶ã¯`kind`ãšããã¿ã°ãæã£ãŠããŸãã`area`é¢æ°ã¯ããã®ã¿ã°ã䜿çšããŠã©ã®åœ¢ç¶ã®é¢ç©ãèšç®ããããå€æããŸãã
Tagged unionã¯ãç¹å®ã®å€ãéãããããã€ãã®ç°ãªãåã®ãã¡ã®1ã€ã§ããããšãè¡šçŸãããšãã«éåžžã«äŸ¿å©ã§ããå€ãã®é¢æ°åããã°ã©ãã³ã°èšèªãæ°ããèšèªïŒäŸ: Rust, TypeScript, Haskellãªã©ïŒã§ã¯ããã®æŠå¿µã¯éåžžã«äžè¬çã§ãã
亀ãããæããªãå (disjoint union): ãã®æã«å±ããéšåéåã®ã©ã®äºã€ãäºãã«çŽ (pairwise disjoint) ã§ãããšãã®ãéåžžã®å䜵ã
Hopeèšèª
Hopeèšèªã§éä¹ããã°ã©ã
çæ¹åãªã¹ãïŒååïŒ