Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Precedence and associativity with infix operators #616

Open
mooreryan opened this issue May 17, 2022 · 0 comments
Open

Precedence and associativity with infix operators #616

mooreryan opened this issue May 17, 2022 · 0 comments

Comments

@mooreryan
Copy link
Contributor

mooreryan commented May 17, 2022

This is related to #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.])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant