Redefine the infix operators - functional-programming

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?

To me, it seems the functions are running in a kind of indefinite
loop, because all the operations seem redefined and connected.
Not really, it's just a simultaneous re-definition of infix operators (with the and keyword). 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 / 1 is actually 5 + (4/1) following the usual precedence rules for arithmetic operators. So, I think the conversion simply preserves this binding (sort of). And you get 5 * (4 - 1) = 15.

The key observation (IMHO) is that (+) is being defined by the preexisting definition of ( * ), not by the one that appears a few lines later. Similarly, ( * ) is being defined by the preexisting definition of (/). As Asiri says, this is because of the use of let rather than let rec.
It's also true that in OCaml, precedence and associativity are inherent in the operators and can't be changed by definitions. Precedence and associativity are determined by the first character of the operator.
If you look at the table of operator precedences and associativities in Section 6.7 of the OCaml Manual, you'll see that all the entries are defined for "operators beginning with character X".

Related

Understanding recursion in Elixir

Forgive me if this is basic but I'm new to Elixir and trying to understand the language.
Say I have this code
defmodule Test do
def mult([]), do: 1
def mult([head | tail]) do
IO.puts "head is: #{head}"
IO.inspect tail
head*mult(tail)
end
end
when I run with this: Test.mult([1,5,10])
I get the following output
head is: 1
[5, 10]
head is: 5
'\n'
head is: 10
[]
50
But I'm struggling to understand what's going on because if I separately try to do this:
[h | t] = [1,5,10]
h * t
obviously I get an error, can someone explain what I'm missing?
Your function breaks down as:
mult([1 | [5, 10]])
1 * mult([5 | [10]])
1 * 5 * mult([10 | []])
1 * 5 * 10 * mult([])
1 * 5 * 10 * 1
50
The '\n' is actually [10] and is due to this: Elixir lists interpreted as char lists.
IO.inspect('\n', charlists: :as_lists)
[10]
Consider the arguments being passed to mult on each invocation.
When you do Test.mult([1,5,10]) first it checks the first function clause; that is can [1,5,10] be made to match []. Elixir will try to make the two expressions match if it can. In this case it cannot so then it tries the next function clause; can [1,5,10] be made to match [head|tail]? Yes it can so it assigns the first element (1) to head and the remaining elements [5,10] to tail. Then it recursively calls the function again but this time with the list [5,10]
Again it tries to match [5,10] to []; again this cannot be made to match so it drops down to [head|tail]. This time head is 5 and tail is 10. So again the function is called recursively with [10]
Again, can [10] be made to match []? No. So again it hits [head|tail] and assigns head = 10 and tail = [] (remember there's always an implied empty list at the end of every list).
Last go round; now [] definitely matches [] so it returns 1. Then the prior head * mult(tail) is evaluated (1 * 10) and that result is returned to the prior call on the stack. Evaluated again head (5) * mult(tail) (10) = 50. Final unwind of the stack head (1) * mult(tail) (50) = 50. Hence the overall value of the function is 50.
Remember that Elixir cannot totally evaluate any function call until it evaluates all subsequent function calls. So it hangs on to the intermediate values in order to compute the final value of the function.
Now consider your second code fragment in terms of pattern matching. [h|t] = [1,5,10] will assign h = 1 and t = [5,10]. h*t means 1 * [5,10]. Since those are fundamentally different types there's no inbuilt definition for multiplication in this case.

Logic of computing a^b, and is power a keyword?

I found the following code that is meant to compute a^b (Cracking the Coding Interview, Ch. VI Big O).
What's the logic of return a * power(a, b - 1); ? Is it recursion
of some sort?
Is power a keyword here or just pseudocode?
int power(int a, int b)
{ if (b < 0) {
return a; // error
} else if (b == 0) {
return 1;
} else {
return a * power(a, b - 1);
}
}
Power is just the name of the function.
Ya this is RECURSION as we are representing a given problem in terms of smaller problem of similar type.
let a=2 and b=4 =calculate= power(2,4) -- large problem (original one)
Now we will represent this in terms of smaller one
i.e 2*power(2,4-1) -- smaller problem of same type power(2,3)
i.e a*power(a,b-1)
If's in the start are for controlling the base cases i.e when b goes below 1
This is a recursive function. That is, the function is defined in terms of itself, with a base case that prevents the recursion from running indefinitely.
power is the name of the function.
For example, 4^3 is equal to 4 * 4^2. That is, 4 raised to the third power can be calculated by multiplying 4 and 4 raised to the second power. And 4^2 can be calculated as 4 * 4^1, which can be simplified to 4 * 4, since the base case of the recursion specifies that 4^1 = 4. Combining this together, 4^3 = 4 * 4^2 = 4 * 4 * 4^1 = 4 * 4 * 4 = 64.
power here is just the name of the function that is defined and NOT a keyword.
Now, let consider that you want to find 2^10. You can write the same thing as 2*(2^9), as 2*2*(2^8), as 2*2*2*(2^7) and so on till 2*2*2*2*2*2*2*2*2*(2^1).
This is what a * power(a, b - 1) is doing in a recursive manner.
Here is a dry run of the code for finding 2^4:
The initial call to the function will be power(2,4), the complete stack trace is shown below
power(2,4) ---> returns a*power(2,3), i.e, 2*4=16
|
power(2,3) ---> returns a*power(2,2), i.e, 2*3=8
|
power(2,2) ---> returns a*power(2,1), i.e, 2*2=4
|
power(2,1) ---> returns a*power(2,0), i.e, 2*1=2
|
power(2,0) ---> returns 1 as b == 0

Fortran pointer to parameter array target

I have a few parameter arrays with different names in a module:
real*8, parameter :: para1(*) = [43.234, 34.0498, ...
real*8, parameter :: para2...
In a routine in this module
subroutine sub(n,...
...
end
I want to use para1 when n=1, para2 when n=2, etc. There are some solutions to that, one is to make an array paras=[para1,para2...] and index properly which works fine. But I want to try using a pointer
real*8, pointer :: ptr(:)
and assign it to different parameter arrays depending on n, but the problem is that "PARAMETER attribute conflicts with TARGET attribute at (1)". If I remove the parameter attribute, the routine is less safe and the SAVE attribute is assumed.
Am I missing something or why can we not combine parameter and target? And is there a good way around it for this purpose?
The parameter and target attributes indeed conflict. An object with the target attribute must be a variable (Fortran 2018 8.5.17, C861); a named constant (object with the parameter attribute) is not a variable (F2018, 8.5.13, C850).
To use target arrays you must, then, use variables. It is tricky to have a variable which is "safe" from having its value modified by a programming mistake or such. There are several considerations which prohibit a variable from appearing in a variable definition context. If you can arrange such a state, then the compiler may have a chance of detecting your mistake. Can that happen easily?
Outside a pure procedure and an intent(in) dummy argument, the most tempting prohibition is with a protected module variable:
module pars
real, save, target, protected :: para1(74) = [...]
real, save, target, protected :: para2(1) = [6]
end module
subroutine sub (...)
use pars
real, pointer :: p
p => para1
end subroutine sub
Being protected, the values are safe from modification outside the module pars? Alas, even if this were true it isn't helpful: being protected, we can't even point a pointer to module variables.
In summary, your compiler isn't going to find it easy to detect a programming mistake which modifies the variable target array, so if you want to use an array as a target, you'll have to be careful.
Following the suggestion by #ja72 in the comment, this is an attempt to use a single 2D array for the parameters. This works nicely with gfortran-8.2 (on MacOS10.11).
program main
implicit none
integer i
integer, parameter :: para1(*) = [1, 2, 3, 4, 5]
integer, parameter :: para2(*) = [6, 7]
integer, parameter :: N1 = size(para1), N2 = size(para2), N = max(N1, N2)
integer, parameter :: params(N, 2) = &
reshape( [ para1, (0, i = 1, N - N1), &
para2, (0, i = 1, N - N2) ], [N, 2] )
print *, "para1 = ", params( :, 1 )
print *, "para2 = ", params( :, 2 )
print *, "Input i"
read *, i
print *, params( :, i )
end
$ gfortran-8 test.f90 && ./a.out
para1 = 1 2 3 4 5
para2 = 6 7 0 0 0
Input i
1
1 2 3 4 5
However, because the code becomes a bit complicated (because of reshape) and may not work with old compilers, things may be more straightforward to just use non-parameter arrays...

Can I use <- instead of = in Julia?

Like in R:
a <- 2
or even better
a ← 2
which should translate to
a = 2
and if possible respect method overloading.
= is overloaded (not in the multiple dispatch sense) a lot in Julia.
It binds a new variable. As in a = 3. You won't be able to use ← instead of = in this context, because you can't overload binding in Julia.
It gets lowered to setindex!. As in, a[i] = b gets lowered to setindex!(a, b, i). Unfortunately, setindex! takes 3 variables while ← can only take 2 variables. So you can't overload = with 3 variables.
But, you can use only 2 variables and overload a[:] = b, for example. So, you can define ←(a,b) = (a[:] = b) or ←(a,b) = setindex!(a,b,:).
a .= b gets lowered to (Base.broadcast!)(Base.identity, a, b). You can overload this by defining ←(a,b) = (a .= b) or ←(a,b) = (Base.broadcast!)(Base.identity, a, b).
So, there are two potentially nice ways of using ←. Good luck ;)
Btw, if you really want to use ← to do binding (like in 1.), the only way to do it is using macros. But then, you will have to write a macro in front of every single assignment, which doesn't look very good.
Also, if you want to explore how operators get lowered in Julia, do f(a,b) = (a .= b), for example, and then #code_lowered f(x,y).
No. = is not an operator in Julia, and cannot be assigned to another symbol.
Disclaimer: You are fully responsible if you will try my (still beginner's) experiments bellow! :P
MacroHelper is module ( big thanks to #Alexander_Morley and #DanGetz for help ) I plan to play with in future and we could probably try it here :
julia> module MacroHelper
# modified from the julia source ./test/parse.jl
function parseall(str)
pos = start(str)
exs = []
while !done(str, pos)
ex, pos = parse(str, pos) # returns next starting point as well as expr
ex.head == :toplevel ? append!(exs, ex.args) : push!(exs, ex)
end
if length(exs) == 0
throw(ParseError("end of input"))
elseif length(exs) == 1
return exs[1]
else
return Expr(:block, exs...) # convert the array of expressions
# back to a single expression
end
end
end;
With module above you could define simple test "language":
julia> module TstLang
export #tst_cmd
import MacroHelper
macro tst_cmd(a)
b = replace("$a", "←", "=") # just simply replacing ←
# in real life you would probably like
# to escape comments, strings etc
return MacroHelper.parseall(b)
end
end;
And by using it you could probably get what you want:
julia> using TstLang
julia> tst```
a ← 3
println(a)
a +← a + 3 # maybe not wanted? :P
```
3
9
What about performance?
julia> function test1()
a = 3
a += a + 3
end;
julia> function test2()
tst```
a ← 3
a +← a + 3
```
end;
julia> test1(); #time test1();
0.000002 seconds (4 allocations: 160 bytes)
julia> test2(); #time test2();
0.000002 seconds (4 allocations: 160 bytes)
If you like to see syntax highlight (for example in atom editor) then you need to use it differently:
function test3()
#tst_cmd begin
a ← 3
a ← a + a + 3 # parser don't allow you to use "+←" here!
end
end;
We could hope that future Julia IDEs could syntax highlight cmd macros too. :)
What could be problem with "solution" above? I am not so experienced julian so many things. :P (in this moment something about "macro hygiene" and "global scope" comes to mind...)
But what you want is IMHO good for some domain specific languages and not to redefine basic of language! It is because readability very counts and if everybody will redefine everything then it will end in Tower of Babel...

Generating random math equation using tree - Avoiding Parentheses

Edit: This was originally on programmers.stackexchange.com, but since I already had some code I thought it might be better here.
I am trying to generate a random math problem/equation. After researching the best (and only) thing I found was this question: Generating random math expression. Because I needed all 4 operations, and the app that I will be using this in is targeted at kids, I wanted to be able to insure that all numbers would be positive, division would come out even, etc, I decided to use a tree.
I have the tree working, and it can generate an equation as well as evaluate it to a number. The problem is that I am having trouble getting it to only use parentheses when needed. I have tried several solutions, that primaraly involve:
Seeing if this node is on the right of the parent node
Seeing if the node is more/less important then it's parent node (* > +, etc).
Seeing if the node & it's parent are of the same type, and if so if the order matters for that operation.
Not that it matters, I am using Swift, and here is what I have so far:
func generateString(parent_node:TreeNode) -> String {
if(self.is_num){
return self.equation!
}
var equation = self.equation!
var left_equation : String = self.left_node!.generateString(self)
var right_equation : String = self.right_node!.generateString(self)
// Conditions for ()s
var needs_parentheses = false
needs_parentheses = parent_node.importance > self.importance
needs_parentheses = (
needs_parentheses
||
(
parent_node.right_node?.isEqualToNode(self)
&&
parent_node.importance <= self.importance
&&
(
parent_node.type != self.type
&&
( parent_node.order_matters != true || self.order_matters != true )
)
)
)
needs_parentheses = (
needs_parentheses
&&
(
!(
self.importance > parent_node.importance
)
)
)
if (needs_parentheses) {
equation = "(\(equation))"
}
return equation.stringByReplacingOccurrencesOfString("a", withString: left_equation).stringByReplacingOccurrencesOfString("b", withString: right_equation)
}
I have not been able to get this to work, and have been banging my head against the wall about it.
The only thing I could find on the subject of removing parentheses is this: How to get rid of unnecessary parentheses in mathematical expression, and I could not figure out how to apply it to my use case. Also, I found this, and I might try to build a parser (using PEGKit), but I wanted to know if anybody had a good idea to either determine where parentheses need to go, or put them everywhere and remove the useless ones.
EDIT: Just to be clear, I don't need someone to write this for me, I am just looking for what it needs to do.
EDIT 2: Since this app will be targeted at kids, I would like to use the least amount of parentheses possible, while still having the equation come out right. Also, the above algorithm does not put enough parentheses.
I have coded a python 3 pgrm that does NOT use a tree, but does successfully generate valid equations with integer solutions and it uses all four operations plus parenthetical expressions. My target audience is 5th graders practicing order of operations (PEMDAS).
872 = 26 * 20 + (3 + 8) * 16 * 2
251 = 256 - 3 - 6 + 8 / 2
367 = 38 * 2 + (20 + 15) + 16 ** 2
260 = 28 * 10 - 18 - 4 / 2
5000 = 40 * 20 / 4 * 5 ** 2
211 = 192 - 10 / 2 / 1 + 24
1519 = 92 * 16 + 6 + 25 + 16
If the python of any interest to you ... I am working on translating the python into JavaScript and make a web page available for students and teachers.

Resources