我有一个OCaml代码:
type primary_color = Red | Green | Blue
let r = Red
type point = float * float
type shape =
| Circle of {center : point; radius : float}
| Rectangle of {lower_left : point; upper_right : point}
let c1 = Circle {center = (0., 0.); radius = 1.}
let r1 = Rectangle {lower_left = (-1., -1.); upper_right = (1., 1.)}
let avg a b =
(a +. b) /. 2.以及计算不同形状中心的下列center函数:
(* Function one using let (...) = ... *)
let center s =
match s with
| Circle {center; radius} -> center
| Rectangle {lower_left; upper_right} ->
let (x_ll, y_ll) = lower_left in
let (x_ur, y_ur) = upper_right in
(avg x_ll x_ur, avg y_ll y_ur)
(* Function two using nested pattern matching Rec{ a = ..., b = ...} *)
let center s =
match s with
| Circle {center; radius} -> center
| Rectangle {lower_left = (x_l, y_l); upper_right = (x_r, y_r)} ->
(avg x_l x_r, avg y_l y_r)
| Point p -> p我不完全理解模式语法在这里的工作方式。在计算中心的第一个和第二个函数中,x_ll和y_ll的值是如何传递给函数avg的?因为a)这对(x_ll, y_ll)没有分配给一个变量,而b)来自对的值只是在不使用let x_ll (a, b) = a的情况下传递
发布于 2021-12-05 20:46:08
两个center函数都完成了相同的任务。第一个问题只是有点迂回而已。虽然第一个与Point不匹配,但前面的代码并没有定义它。
如果仍然需要这两个元组的名称,可以使用as。
let center s =
match s with
| Circle {center; radius} -> center
| Rectangle {lower_left = (x_l, y_l) as ll;
upper_right = (x_r, y_r) as ur} ->
(avg x_l x_r, avg y_l y_r)结构模式匹配功能非常强大,而且并不局限于一定数量的级别。考虑一个非常简单的例子。
type a = {b: int}
type c = {d: a}
type e = {f: c}
let g = {f={d={b=42}}}我们可以直接匹配那个int。
match g with
| {f={d={b=n}}} -> n甚至忽略了=n。
match g with
| {f={d={b}}} -> b我们也可以在let绑定中这样做。
let {f={d={b=n}}} = g in
nhttps://stackoverflow.com/questions/70238154
复制相似问题