gpt4 book ai didi

erlang - 为什么 OCaml 的模式匹配比 Erlang 的弱?

转载 作者:行者123 更新时间:2023-12-04 09:13:59 24 4
gpt4 key购买 nike

我是 OCaml 的新手,正在阅读 Real World OCaml (RWO) 一书。模式匹配在第 3 章中进行了描述,与 Erlang(或 Prolog)的模式匹配相比,它似乎很弱。

我的问题是:

  • 为什么 OCaml 的模式匹配较弱?
  • OCaml 的模式匹配风格有什么优势吗?

  • 一个具体的例子:

    以下函数(取自 RWO 第 63 页)消除了一个列表
    let rec destutter list =
    match list with
    | [] -> []
    | [hd] -> [hd]
    | hd :: hd' :: tl ->
    if hd = hd' then ds1 (hd' :: tl)
    else hd :: ds1 (hd' :: tl)
    ;;

    # destutter [1;2;3;3;4;5;5;6];;
    - : int list = [1; 2; 3; 4; 5; 6]

    在 Erlang 中,可以(我认为更喜欢)使用模式匹配而不是条件匹配:
    destutter([])      -> [];
    destutter([X]) -> [X];
    destutter([H,H|T]) -> destutter([H|T]);
    destutter([H|T]) -> [H | destutter(T)].

    在 OCaml 中尝试这种事情......
    let rec destutter list =
    match list with
    | [] -> []
    | [hd] -> [hd]
    | hd :: hd :: tl -> destutter tl (* error *)
    | hd :: tl -> hd :: destutter tl
    ;;

    ...在标记的行上引发错误:
    Error: Variable hd is bound several times in this matching

    因此,Erlang/Prolog 风格的模式匹配在 OCaml 中不起作用。为什么? OCaml 方法的优点是什么?

    带着感谢和最美好的祝愿

    伊万

    最佳答案

    Erlang 模式更强大,因为它可以匹配运行时确定的内容。 OCaml 模式与编译时固定的内容相匹配。因此,OCaml 模式可能会变得更快。我还发现 OCaml 风格的模式更容易推理。

    关于erlang - 为什么 OCaml 的模式匹配比 Erlang 的弱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956003/

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