简体   繁体   中英

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

I am trying to write a function of type nat -> nat -> nat -> nat which i named sudan_nat it works on the principle of sudan 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

This is the code i wrote for the sudan_nat

My case for testing output is ((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)))))

This is the result for left side

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

This is the result of right side i have been scratching my head for hours now any kind of suggestion is welcomed thank you

four_nat is Succ (Succ (Succ (Succ Zero))) . That's 4 Succ constructors. You've added 3 of these together, so you have... 12. 4 times 3 = 12.

When it comes to evaluating sudan_nat nat_one nat_two nat_two it breaks down:

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))))

As an additional style suggestion, you may wish to define a module to organize your code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM