gpt4 book ai didi

sml - SML/NJ 中的关键字 "as"

转载 作者:行者123 更新时间:2023-12-03 20:30:13 28 4
gpt4 key购买 nike

我最近看到有人使用 as在他们的 SML/NJ 计划中。我找到的最有用的引用是 "as" keyword in OCaml .

虽然 OCaml 也属于 ML 编程语言家族,但它们是不同的。例如,在上一个答案中给出的示例程序中,

let rec compress = function
| a :: (b :: _ as t) -> if a = b then compress t else a :: compress t
| smaller -> smaller;;

我将它翻译成 SML/NJ 是(如果我做错了,请纠正我)
fun compress (a :: (t as b :: _)) = if a = b then compress t else a :: compress t
| compress smaller = smaller

如您所见,模式 (b :: _ as t)订单不同于 (t as b :: _)在第二个片段中。 (不过,它们的用法几乎相同)

对于可能的答案,我希望它可以包含 (1) 对此关键字的引用 as在 SML/NJ 的官方文档、类(class)和书籍中的任何一个和“也许”(2) 中的一些示例来说明其用法。我希望这个问题可以帮助 future 的用户看到 as .

最佳答案

as关键字是标准 ML 定义('97 修订版)的一部分。见 page 79, figure 22 (突出我的):

enter image description here

这些在 Haskell 和几乎任何其他允许将标识符绑定(bind)到(子)模式的语言中称为 as-patterns,但名称的来源显然来自 ML。

它的目的是为模式或其中的一部分命名。例如,我们可以捕获 2 元组列表的整个头部,同时为元组的值分配名称。

fun example1 (list : (int * string) list) =
case list of
(* `head` will be bound to the tuple value *)
(* `i` will be bound to the tuple's 1st element *)
(* `s` will be bound to the tuple's 2nd element *)
head as (i, s) :: tail => ()
| nil => ()

另一种用法出现在记录模式中。请注意,乍一看,它可能给人的印象是 as-name 现在位于 as 的右侧。关键字,但不是(请参见下面的组合示例):
fun example2 (list : { foo: int * string } list) =
case list of
(* `f` will be found to the value of the `foo` field in the record. *)
{ foo as f } :: tail => ()

(* The above can also be expressed as follows *)
| { foo = f } :: tail => ()

| nil => ()

还有一个组合示例,您可以在其中看到 as记录中的用法与其他地方的用法一致,即名称位于 as 的左侧。关键字(这里的名称是记录标签)。
fun example3 (list : { foo: int * string } list) =
case list of
head as { foo as (i, s) } :: tail => ()

(* This is valid, too, but `foo` is not a binding. *)
| head as { foo = (i, s) } :: tail => ()

(* Here, `f` is bound to the whole tuple value. *)
| head as { foo = f as (i, s) } :: tail => ()

| nil => ()

关于sml - SML/NJ 中的关键字 "as",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49840954/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com