簡體   English   中英

我開始在 ocaml 工作,我無法弄清楚關於 nat 類型的小事

[英]I started working in ocaml and i can't figure out a small thing about nat types

我正在嘗試編寫類型為 nat -> nat -> nat -> nat 的 function,我將其命名為 sudan_nat 它按照蘇丹 function 的原則工作 **

Wikipedia:
   https://en.wikipedia.org/wiki/Sudan_function

//This is the type definition
type nat = Zero | Succ of nat

let add_nat m n =
  let rec helper m = match m with Zero -> n | Succ m -> Succ (helper m)
  in helper m

let zero_nat = Zero
let one_nat  = Succ zero_nat             
let two_nat  = Succ one_nat             
let four_nat  = add_nat two_nat two_nat`



let sudan_nat m n p = 
  let rec helper m n = match m with Zero -> n | Succ m -> Succ (helper m n)
  in helper (add_nat (add_nat m n) p) one_nat

這是我為 sudan_nat 寫的代碼

我測試 output 的情況是 ((sudan_nat one_nat two_nat two_nat) = (add_nat (add_nat four_nat four_nat) four_nat))

Succ (Succ (Succ (Succ (Succ (Succ Zero)))))

這是左側的結果

Succ
 (Succ
   (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))

這是右側的結果我已經摸索了幾個小時現在歡迎任何建議謝謝

four_natSucc (Succ (Succ (Succ Zero))) 那是 4 個Succ構造函數。 你把其中的 3 個加在一起,所以你有... 12。4 乘以 3 = 12。

當談到評估sudan_nat nat_one nat_two nat_two時,它分解了:

sudan_nat nat_one nat_two nat_two
helper (add_nat (add_nat nat_one nat_two) nat_two) one_nat
helper (add_nat (add_nat Zero nat_two) nat_two) one_nat
helper (add_nat nat_two nat_two) one_nat
helper nat_four one_nat
...
Succ (Succ (Succ (Succ (Succ Zero))))

作為額外的風格建議,您可能希望定義一個模塊來組織您的代碼。

module Nat =
struct
  type t = Zero | Succ of t
  
  let add m n =
    let rec helper m = 
      match m with 
      | Zero -> n 
      | Succ m -> Succ (helper m)
    in 
    helper m

  let one = Succ Zero
  let two = Succ (Succ Zero)
  let four = add two two
  
  let sudan m n p = 
    let rec helper m n = 
      match m with 
      | Zero -> n 
      | Succ m -> Succ (helper m n)
    in 
    helper (add (add m n) p) one
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM