2016-08-10 57 views
5

我對OCaml中的and關鍵字感到困惑。通過this code看,我看到OCaml中的`和`關鍵字是什麼意思?

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關鍵字是否僅複製最後的type,letlet rec聲明?有沒有像and rec聲明那樣的東西?爲什麼我要使用and而不是隻輸入lettype,這使得我的代碼不易變得重構?還有什麼我應該知道的嗎?

回答

13

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」,然後與標籤的b'和「c」的一個兩個節點樹將被表示爲:

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 
相關問題