【问题标题】:What does the `and` keyword mean in OCaml?OCaml 中的“and”关键字是什么意思?
【发布时间】:2016-12-17 11:47:46
【问题描述】:

我对 OCaml 中的 and 关键字感到困惑。翻看this code,我明白了

type env = {
    (* fields for a local environment described here *)
}

and genv {
    (* fields for a global environment here *)
}

然后later

let rec debug stack env (r, ty) = (* a function definition *)

and debugl stack env x = (* another function definition *)

这里发生了什么? and 关键字是否只是复制最后一个 typeletlet rec 语句?是否有 and rec 声明之类的东西?为什么我要使用and 而不是只输入lettype,从而使我的代码在重构时不那么脆弱?还有什么我应该知道的吗?

【问题讨论】:

    标签: syntax ocaml


    【解决方案1】:

    and 关键字用于避免多个 let(第一个示例,我从不使用它,但为什么不使用它)或用于类型、函数、模块的相互递归定义...

    正如您在第二个示例中看到的那样:

    let rec debug stack env (r, ty) =
       ...
       | Tunresolved tyl -> o "intersect("; debugl stack env tyl; o ")"
       ...
     
     and debugl stack env x =
       ...
       | [x] -> debug stack env x
       ...
    

    debug 调用debugl,反之亦然。所以and 允许这样做。

    [编辑] 没有给出一个合适的例子让我很困扰,所以这里有一个你经常会看到的例子:

     let rec is_even x =
       if x = 0 then true else is_odd (x - 1)
     and is_odd x =
       if x = 0 then false else is_even (x - 1)
    

    (你可以找到这个例子here

    对于相互递归的类型,很难找到配置,但遵循 this wikipedia page 我们将定义 treesforests 如下

     type 'a tree = Empty | Node of 'a * 'a forest
     and 'a forest = Nil | Cons of 'a tree * 'a forest
    

    例如,由空树、标记为a 的单例树和标记为bc 的两节点树组成的森林将表示为:

     let f1 = Cons (Empty, (* Empty tree *)
                 Cons (Node ('a',  (* Singleton tree *)
                             Nil), (* End of the first tree *)
                       Cons (Node ('b', (* Tree composed by 'b'... *)
                                   Cons (Node ('c', (* and 'c' *)
                                               Nil), 
                                         Nil)
                               ),
                             Nil (* End ot the second tree *)
                         )
                   )
             );;
      
    

    大小函数(计算森林中的节点数)将是:

    let rec size_tree = function
      | Empty -> 0
      | Node (_, f) -> 1 + size_forest f
    and size_forest = function
      | Nil -> 0
      | Cons (t, f) -> size_tree t + size_forest f
    

    我们得到

    # size_forest f1;;
    - : int = 3
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2011-02-14
      • 2010-10-29
      • 2011-10-28
      • 1970-01-01
      • 2011-11-23
      相关资源
      最近更新 更多