Sean
Sean

Reputation: 3450

OCaml Adding Natural Numbers

I'm learning OCaml in school and recently came came across a program for an assignment that I couldn't understand, and was hoping if somebody could explain it to me. Here's the code:

(* Natural numbers can be defined as follows:
   type = ZERO | SUCC of nat;;

   For instance, two = SUCC (SUCC ZERO) and three = SUCC (SUCC (SUCC ZERO)).

  Write a function 'natadd' that adds two natural numbers in this fashion. *)

# type = ZERO | SUCC of nat;;
# let two = SUCC (SUCC ZERO);;
# let three = SUCC (SUCC (SUCC ZERO));;
# let rec natadd : nat -> nat -> nat =
    fun n1 n2 ->
      match n1 with
      | ZERO -> n2
      | SUCC n1 -> SUCC (natadd n1 n2)
  ;;

Here's a sample output for the code:

# natadd two three;;
- : nat = SUCC (SUCC (SUCC (SUCC (SUCC ZERO))))

What I don't understand is the match-with statement. Does it mean that if n1 is non-zero, then it adds SUCC and uses [SUCC n1] as a new argument in place of n1 for the recursive call?

Upvotes: 1

Views: 1159

Answers (1)

Bergi
Bergi

Reputation: 665364

No, it doesn't use SUCC n1 as the argument of the recursive call, it uses only n1 (the part of the matched SUCC) as the argument. The SUCC is then applied to the result of the recursive call.

The code might be a bit confusing because there are two variables with the name n1. Better might be

let rec natadd : nat -> nat -> nat = fun a b ->
  match a with
  | ZERO -> b
  | SUCC a_pred -> SUCC (natadd a_pred b)

Upvotes: 3

Related Questions