You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中使用GADTs实现穷举检查的简洁写法(无需幻影特质)

Scala中实现OCaml风格的穷举匹配(无需幻影特质)

需求背景

希望在Scala中实现与以下OCaml代码相同的行为:编译器能识别匹配是穷举的,因为已声明两个 scrutinee 必须具有相同类型。

OCaml 示例代码

type circle
type rectangle

type _ figure =
    | Circle : int -> circle figure
    | Rectangle : int * int -> rectangle figure

let equal_figure : type a. a figure -> a figure -> bool = fun f1 f2 -> match (f1, f2) with
| Circle r1, Circle r2 -> Int.(r1 = r2)
| Rectangle (x1, y1), Rectangle (x2, y2) -> Int.(x1 = x2 && y1 = y2)
(* 编译器知道该匹配是穷举的 *)

当前Scala实现(带幻影特质)

我已经将示例直接移植到Scala,穷举检查器可以正常工作,但用到了幻影特质CircleMarker和RectangleMarker:

sealed trait CircleMarker
sealed trait RectangleMarker

enum Fig[T]:
  case Circle(r: Int) extends Fig[CircleMarker]
  case Rectangle(x: Int, y: Int) extends Fig[RectangleMarker]

def equalFig[T](f1: Fig[T], f2: Fig[T]): Boolean = (f1, f2) match
  case (Fig.Circle(r1), Fig.Circle(r2))               => r1 == r2
  case (Fig.Rectangle(x1, y1), Fig.Rectangle(x2, y2)) => x1 == x2 && y1 == y2
(* 编译器知道该匹配是穷举的 *)

问题

是否存在更简洁的Scala表达方式,无需使用CircleMarker和RectangleMarker这类幻影特质?


内容的提问来源于stack exchange,提问作者Max Heiber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:42:38