Why does this recursion MyFunc[n_] := MyFunc[n] = 2; end? - recursion

I don't understand, why does this recursion end:
In[27]:= MyFunc[n_] := MyFunc[n] = 2;
MyFunc[3]
Out[28]= 2
Shouldn't it be endless
MyFunc[3]
MyFunc[3] = 2
(MyFunc[3] = 2) = 2
and so on?
Why does this
MyFunc[n_] := MyFunc[n];
MyFunc[3]
During evaluation of In[31]:= $IterationLimit::itlim: Iteration limit of 4096 exceeded. >>
Out[33]= Hold[MyFunc[3]]
cause "iteration" limit error, not recursion limit?

My other answer glossed over some important details. Here's a second and, I hope, better one:
SetDelayed has the attribute HoldAll while Set has the attribute HoldFirst. So, your definition
MyFunc[n_] := MyFunc[n] = 2;
is stored with no part evaluated. Only when you call it, eg MyFunc[3] is the rhs evaluated, in this case to an expression involving Set, MyFunc[3] = 2. Since Set has attribute HoldFirst this rule is stored with its first argument (ie the lhs) unevaluated. At this stage MyFunc[3], the lhs of the Set expression is not re-evaluated. But if it were, Mathematica would find the rule MyFunc[3] = 2 and evaluate MyFunc[3] to 2 without using the rule with lhs MyFunc[n_].
Your second definition, ie
MyFunc[n_] := MyFunc[n];
is also stored unevaluated. However, when you call the function, eg myFunc[3], the rhs is evaluated. The rhs evaluates to MyFunc[3] or, if you like, another call to MyFunc. During the evaluation of MyFunc[3] Mathematica finds the stored rewrite rule MyFunc[n_] := MyFunc[n] and applies it. Repeatedly. Note that Mathematica regards this as iteration rather than recursion.
It's not entirely clear to me what evaluating the lhs of an expression might actually mean. Of course, a call such as MyFunc[3+4] will actually lead to MyFunc[7] being evaluated, as Mathematica greedily evaluates arguments to function calls.
In fact, when trying to understand what's going on here it might be easier to forget assignment and left- and right-hand sides and remember that everything is an expression and that, for example,
MyFunc[n_] := MyFunc[n] = 2;
is just a way of writing
SetDelayed[MyFunc[n_], MyFunc[n] = 2]

Related

Declare a dynamic constant in Maxima

I need to declare a variable as constant, the variable is generated while the program is running, I tried this way:
foo(var) := declare(''var, constant)$
foo(x)$
facts();
But that doesn't work and I get:
[kind(var, constant)]
everytime.
instead:
[kind(x, constant)]
When I write code without a function, everything works fine:
var: x$
declare(''var, constant)$
facts();
I get:
[kind(x, constant)]
Does anyone know how to do this dynamically via a function?
The conventional way to ensure that arguments are evaluated, even for functions which otherwise quote their arguments, is to apply the function to the arguments. E.g.:
apply (declare, [var, 'constant]);
Or, in a function:
foo(var) := apply (declare, [var, 'constant]);
apply evaluates its arguments, so the arguments are evaluated by the time the function sees them.
The quote-quote ''var doesn't have the expected effect in a function because quote-quote is applied only at the time the expression is parsed. So any later assignment to var has no effect.
I recommend against eval_string. There is almost always a better way to do anything than string processing; in this case that better way is apply.

How does lexical scoping with recursive iterators work?

This particular example function is in Lua, but I think the main concepts are true for any language with lexical scoping, first-class functions, and iterators.
Code Description (TL;DR -- see code):
The code below defines an iterator constructor which merely defines a local value and returns an iterator function.
This iterator function, when run, uses the local value from the constructor and increases that value by 1. It then runs itself recursively until the value reaches 5, then adds 1 to the value and returns the number 5. If it's run again, it will run itself recursively until the value reaches 20 or higher, then it returns nil, which is the signal for the loop to stop.
I then run an outer loop using the iterator provided by the constructor, which will run the body of the loop when the iterator returns a value (5). In the body of the outer loop I put an inner loop that also uses an iterator provided by the constructor.
The program should run the body of the loop once (when the value in the outer loop iterator hits 5) and then run the inner loop completely (letting the inner loop value hit 20), then return back to the outer loop and run it until it finishes.
function iterConstr()
local indexes = {0}
function iter()
print(indexes[1])
indexes[1] = indexes[1] + 1
if indexes[1] == 5 then
indexes[1] = indexes[1] + 1
return 5
elseif indexes[1]>=21 then
print("finished!")
return nil
else
print("returning next one")
return iter()
end
end
return iter
end
for val in iterConstr() do
for newVal in iterConstr() do
end
print("big switch")
end
The behavior I did not expect is that the value from the inner loop and outer loop seem to be linked together. When focus is returned to the outer loop after running through the inner loop, it runs with the expected next value for the outer loop (6), but then instead of iterating and incrementing up to 20, it instead jumps immediately to 21, which is where the inner loop ended!
Can anyone help explain why this bizarre behavior occurs?
I believe your problem lies on line 3 - you declare iter as a global function instead of a local one, which makes it accessible from any Lua chunk. Changing that line to local function iter() corrects this behaviour. I think therefore that this is more of an issue with the developer applying lexical scoping than with lexical scoping itself :)

Tell if number is odd or even with SML

This is the second SML program I have been working on. These functions are mutually recursive. If I call odd(1) I should get true and even(1) I should get false. These functions should work for all positive integers. However, when I run this program:
fun
odd (n) = if n=0 then false else even (n-1);
and
even (n) = if n=0 then true else odd (n-1);
I get:
[opening test.sml]
test.sml:2.35-2.39 Error: unbound variable or constructor: even
val it = () : unit
How can I fix this?
The problem is the semicolon (;) in the middle. Semicolons are allowed (optionally) at the end of a complete declaration, but right before and is not the end of a declaration!
So the compiler is blowing up on the invalid declaration fun odd (n) = if n=0 then false else even (n-1) that refers to undeclared even. If it were to proceed, it would next blow up on the illegal occurrence of and at the start of a declaration.
Note that there are only two situations where a semicolon is meaningful:
the notation (...A... ; ...B... ; ...C...) means "evaluate ...A..., ...B..., and ...C..., and return the result of ...C....
likewise the notation let ... in ...A... ; ...B... ; ...C... end, where the parentheses are optional because the in ... end does an adequate job bracketing their contents.
if you're using the interactive REPL (read-evaluate-print loop), a semicolon at the end of a top-level declaration means "OK, now actually go ahead and elaborate/evaluate/etc. everything so far".
Idiomatic Standard ML doesn't really use semicolons outside of the above situations; but it's OK to do so, as long as you don't start thinking in terms of procedural languages and expecting the semicolons to "terminate statements", or anything like that. There's obviously a relationship between the use of ; in Standard ML and the use of ; in languages such as C and its syntactic descendants, but it's not a direct one.
I'm sure there's a didactic point in making these functions recursive, but here's some shorter ones:
fun even x = x mod 2 = 0
val odd = not o even

Why the "=" R operator should not be used in functions?

The manual states:
The operator ‘<-’ can be used anywhere,
whereas the operator ‘=’ is only allowed at the top level (e.g.,
in the complete expression typed at the command prompt) or as one
of the subexpressions in a braced list of expressions.
The question here mention the difference when used in the function call. But in the function definition, it seems to work normally:
a = function ()
{
b = 2
x <- 3
y <<- 4
}
a()
# (b and x are undefined here)
So why the manual mentions that the operator ‘=’ is only allowed at the top level??
There is nothing about it in the language definition (there is no = operator listed, what a shame!)
The text you quote says at the top level OR in a braced list of subexpressions. You are using it in a braced list of subexpressions. Which is allowed.
You have to go to great lengths to find an expression which is neither toplevel nor within braces. Here is one. You sometimes want to wrap an assignment inside a try block: try( x <- f() ) is fine, but try( x = f(x) ) is not -- you need to either change the assignment operator or add braces.
Expressions not at the top level include usage in control structures like if. For example, the following programming error is illegal.
> if(x = 0) 1 else x
Error: syntax error
As mentioned here: https://stackoverflow.com/a/4831793/210673
Also see http://developer.r-project.org/equalAssign.html
Other than some examples such as system.time as others have shown where <- and = have different results, the main difference is more philisophical. Larry Wall, the creater of Perl, said something along the lines of "similar things should look similar, different things should look different", I have found it interesting in different languages to see what things are considered "similar" and which are considered "different". Now for R assignment let's compare 2 commands:
myfun( a <- 1:10 )
myfun( a = 1:10 )
Some would argue that in both cases we are assigning 1:10 to a so what we are doing is similar.
The other argument is that in the first call we are assigning to a variable a that is in the same environment from which myfun is being called and in the second call we are assigning to a variable a that is in the environment created when the function is called and is local to the function and those two a variables are different.
So which to use depends on whether you consider the assignments "similar" or "different".
Personally, I prefer <-, but I don't think it is worth fighting a holy war over.

Guarantying assignment to a function's return value in OCaml

Coming to OCaml from Lisp, I find myself very confused about when functions return and when they don't. I miss my magic Quote! Thankfully, most of the time, OCaml appears to automagicly know when I want a function evaluated and when I don't. However, I frequently find myself trying to assign the return value of a function in a let expression, like the following.
let start = Sys.time in
(*
* do something here
*)
;
let ending = Sys.time in
Printf.printf "did something in %f seconds\n" (ending -. start)
but then ocamlc complains
Error: This Expression has type unit -> float
but an expression was expected of type float
Telling me that start and end are bound to Sys.time, not the return value of Sys.time.
Is this behavior I'm trying to get not OCamly? Do I want to be doing things another way? Am I just missing something completely obvious?
A function is evaluated when you apply it to an argument. I.e. when you do f, f never gets evaluated. When you do f x, f always gets evaluated. There's nothing magical about it.
As you correctly pointed out, Sys.time is a function (of type unit -> float) and let start = Sys.time just assigns that function to start.
To get the behavior you want simply do let start = Sys.time (), which applies the function Sys.time to the argument () (which is the only value of type unit).
You cannot call a function just by writing its name. If you just write a function's name, you're returning the function itself, not its return value. That error is telling you that the function takes a unit argument — i.e., you should write Sys.time () to actually apply the function and get the resulting float value.
To help people used to Lisp, I would say that there are only two evaluation rules in OCAML:
Delayed evaluation rule: A function value, such as fun x -> body, when not applied to any argument, will not be evaluated any further. (The evaluation of a function body is “delayed”.) Instead, the expression “body” is compiled into computer code. That computer code is the real “value” of the function expression, and the code will be run whenever the function is applied to an argument.
Eager evaluation rule: In evaluating f x, the argument x is evaluated first. (Functions are “eager to evaluate their arguments”.) Then the function expression f is evaluated, which generally yields a function value such as fun x -> body. (Here, body is not yet evaluated; only as much is evaluated that we get a function value fun x -> body. For example, f could be a complicated expression that yields such a function value as a result.) Finally, the body of the resulting function is applied to the actually computed value of the argument (i.e. the body is evaluated with x substituted by the computed value of the argument).
For this reason, you can implement "quote" in OCAML, if you want to delay the evaluation of some expression, only by putting it inside the body of a function expression. For example, if you have previously computed f by let f = fun x->x+1 and now you want to delay the evaluation of f 3, you can put this f 3 into the body of a function:
let delay_f () = f 3;;
Now you will get 4 only when you evaluate delay_f (). You can pass the value delay_f to another function, and f 3 will stay unevaluated until somebody evaluates delay_f ().

Resources