owl
owl copied to clipboard
Precedence and associativity with infix operators
This is related to https://github.com/owlbarn/owl/issues/21.
The infix operators seem to break with what you would expect normal math operator precedence to have. I'm just wondering if this is the intended behavior or not.
Here's an example.
# module M = Owl.Mat;;
# module Op = Owl.Dense.Matrix.Operator;;
# let x = M.linspace 0. 10. 6
val x : M.mat =
C0 C1 C2 C3 C4 C5
R0 0 2 4 6 8 10
(* Okay *)
# Op.(x *$ 2. +$ 1.);;
- : (float, Bigarray.float64_elt) Owl_dense_matrix_generic.t =
C0 C1 C2 C3 C4 C5
R0 1 5 9 13 17 21
(* Not what you would expect... *)
# Op.(2. $* x +$ 1.);;
- : (float, Bigarray.float64_elt) Owl_dense_matrix_generic.t =
C0 C1 C2 C3 C4 C5
R0 2 6 10 14 18 22
I assume this is because of OCaml's rules about operator precedence and associativity. Particularly the fact that operators starting with +
(like +$
) have a higher precedence than those starting with $
(like $*
).
So then you have a case where scalar * matrix
multiplication ($*
) has a lower precedence than matrix * scalar
multiplication (*$
).
In particular, you can see that, scalar * matrix
multiplication ($*
) has a lower precedence than matrix + scalar
(+$
) addition.
Just for reference, here is numpy with the same example.
>>> import numpy as np
>>> x = np.linspace(0, 10, num=6)
>>> 2 * x + 1
array([ 1., 5., 9., 13., 17., 21.])
>>> x * 2 + 1
array([ 1., 5., 9., 13., 17., 21.])