Why is it giving me this error? This expression has type Z.t but an expression was expected of type int

Viewed 74

EDITED: Alright, this is the complete error :

45 |               | _ -> Z.of_int 3 * Z.(s1 (num-1)) + Z.(sum_s1 num)
                  ^^^^^^^^^^
Error: This expression has type Z.t but an expression was expected of type
         int 

And this is the code in question :

let rec s1 num =
              match num with
               | 0 -> Z.of_int(1)
               | 1 -> Z.of_int(2)
               | _ -> Z.of_int 3 * Z.(s1 (num-1)) + Z.(sum_s1 num)
            and
              sum_s1 num =
               let rec sum_s1_impl (num, k) =
                 if (num-2 < 1) || (k > num-2) then 0
                 else (s1 k) * (s1 (num-k-1)) + (sum_s1_impl (num, k+1))
               in sum_s1_impl (num, 1);;

I don't know where is the problem/how can I fix it (some tips)

Thanks!!

EDIT#2 :

let rec s1 num =
              match num with
               | 0 -> Z.of_int(1)
               | 1 -> Z.of_int(2)
               | _ -> Z.of_int(3 * (s1 (num-1)) + (sum_s1 num))
            and
              sum_s1 num =
               let rec sum_s1_impl (num, k) =
                 if (num-2 < 1) || (k > num-2) then 0
                 else (s1 k) * (s1 (num-k-1)) + (sum_s1_impl (num, k+1))
               in sum_s1_impl (num, 1);;

Even with the use of Z.of_int(3 * (s1 (num-1)) + (sum_s1 num)) I stil get the same error

2 Answers

Generally speaking you need to carefully track which of your parameters are of type int (ordinary OCaml integer) and which are Z.t (big integer). You seem to treat them as if they're the same type, which doesn't work in a strongly typed language.

The first reported error is for this expression:

Z.of_int 3 * Z.(s1 (num-1)) + Z.(sum_s1 num)

If I look at the code for s1 it shows that it expects an int parameter, since it matches the parameter against 0, 1, etc. Similarly, the code for sum_s1 expects an int parameter since it applies the built-in - operator to the parameter.

With these assumptions, the first problem in this expression is that Z.of_int returns a big integer (Z.t). You can't multiply a big integer using the built-in * operator.

But note that this subexpression looks wrong also:

Z.(s1 (num - 1))

Since the expression is prefixed with Z., the operators will come from the Z module. Hence the - is of type Z.t -> Z.t -> Z.t. But you're applying it to num and 1 which are ordinary OCaml ints.

You need to go through the expressions and figure out the type you want for each subpart. Generally you want to do everything using big integers, so you should convert using Z.of_int whenever you have a regular OCaml int. Most of the parameters and return values of your functions should (in my opinion) be big integers.

Related