I am learning Jason Hickey’s Introduction to Objective Caml.
Just have a question about Redefine the infix operators.
So in the book, there is such a paragraph:
# let (+) = ( * )
and (-) = (+)
and ( * ) = (/)
and (/) = (-);;
val + : int > int > int = <fun>
val - : int > int > int = <fun>
val * : int > int > int = <fun>
val / : int > int > int = <fun>
# 5 + 4 / 1;;
-: **int = 15**
First, how does these redefinition work?
To me, it seems the functions are running in a kind of indefinite loop, because all the operations seem redefined and connected.
for example, if I do 1+2, then it will be 1 * 2 and since ( * ) = (/), it will be then 1 / 2 and since (/) = (-), then it will be 1-2, so on so forth. Am I right?
Second, will the result of 5 + 4 / 1 be 15, even if the functions are executed only one step further in the redefinition?
So assume the redefinition will be execute one step further, i.e., 1 + 2 will only be 1 * 2 and no more transform, so 5 + 4 / 1 should be 5 * 4 -1, right? then the answer is 19. Am I correct?
Not really, it’s just a simultaneous re-definition of infix operators (with the
andkeyword). What you see is not a recursive definition. In OCaml, recursive definitions are made with let rec (as you may already know).For the second part of the question, I think it’s a matter of operator precedence. Note that in the original expression
5 + 4 / 1is actually5 + (4/1)following the usual precedence rules for arithmetic operators. So, I think the conversion simply preserves this binding (sort of). And you get5 * (4 - 1) = 15.