vent
vent

Reputation: 39

Modify a matrix in ocaml

I want to write a function that is modify every elements inside a matrix. But I have some problem when compiling.

Warning 10: this expression should have type unit.

I think because all function in ocaml need to return to a value or unit, so if I implement two tasks inside one function, it is not acceptable. Please help me to fix it.

let nomalize_matrix d a x = 
 for i = 1 to d do 
      for j = 1 to d do
          let n = i*j in
          x.(i)(j) = sprintf "%s_%d" a n
      done
  done;
x;;

Upvotes: 1

Views: 951

Answers (2)

alifirat
alifirat

Reputation: 2937

Just be careful to do not use the operator "=" when you set one item from an array and use the operator "<-" instead so in your code, you have this :

let nomalize_matrix d a x = 
 for i = 1 to d do 
      for j = 1 to d do
          let n = i*j in
          x.(i)(j) <- sprintf "%s_%d" a n
      done
  done;
x;;

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

In an expression the = operator in OCaml is a comparison operator that tests for equality. To assign to an array, use the <- operator.

The compiler is complaining because your expression has type bool (i.e., the result of the comparison). The expression in a for should have type unit since its return value is ignored. And indeed, the <- operator returns (), the unit value.

To access an element of a two-dimensional array, the syntax looks like: x.(i).(j). Note the extra dot, not present in your code.

There is no problem in general with doing two things in a function. You can separate two expressions with ; if the first has type unit. The result is the value of the second expression. Your code is OK in this respect.

Upvotes: 4

Related Questions