Automatically assigning name to a list created by iteration - maxima

I am currently trying to create a command for maxima that allows for iteration of a function and places the result in a list. I managed to create the iteration through a loop, and it successfully places the results in a list.
However, I would like that list's name to be assigned when the user does the input. I tried using makelist command or direct naming built into the function but it doesn't work.
FunctionIterationList(f,a,j,listname):= block(
b:a,
s: [],
for iteraciones: 0 thru j do
(
b: f(b),
s: cons([iteraciones,bfloat(b)],s)
),
listname: reverse(s));
This would be an example of the result with the current code
FunctionIterationList(f(x):=x+1,0,10,asdf);
[[0,1.0b0],[1,2.0b0],[2,3.0b0],[3,4.0b0],[4,5.0b0],[5,6.0b0],[6,7.0b0],[7,8.0b0],[8,9.0b0],[9,1.0b1],[10,1.1b1]]

I see a couple of ways to get to a solution.
(1) You can fix up the existing function definition by using the :: assignment operator instead of :, since :: means to assign the value of the right-hand side to the value of the left-hand side. E.g. after x: 'asdf, then x :: 123 assigns 123 to asdf, not to x.
So in your function definition you could say listname :: reverse(s) at the end.
(2) Another way to go about it is by using the built-in function makelist, e.g.
asdf: makelist (x + 1, x, 0, 10);
or
asdf: makelist (f(x), x, 0, 10);
when f is the function you want.

Related

How to write a recursive anonymous function in Dart

Lets say I wanted to write a recursive anonymous function to calculate factorial values.
print(((int a) => a == 1? 1 : a * this(a - 1))(4));
I would expect this to print 24, which is 4! (this function is obviously prone to issues with negative numbers, but that's beside the point)
The problem is that this doesn't refer to the anonymous function in order to make a recursive call.
Is this something that's possible in dart? I've seen it in python before, where a function is assigned to a variable with the walrus operator ( := ) and is also recursive.
Here is an example that creates a list of the average value on each level of a binary tree:
return (get_levels := lambda l: ([mean(node.val for node in l)] + get_levels([child for node in l for child in [node.left, node.right] if child])) if l else [])([root])
As you can see, the lambda is called get_levels. It calculates the average of the current level, then makes a recursive call on the next level of the binary tree and appends it to the list of previous level averages.
The closest that I could come up with is this:
var getLevels;
List<double> averageOfLevels(TreeNode? root) {
return root == null ? [] : (getLevels = (List<TreeNode> level) => level.isNotEmpty ? <double>[level.map((node) => node.val).fold(0, (int l, int r) => l+r) / level.length] + getLevels([for(var node in level) ...[node.left, node.right]].whereType<TreeNode>().toList()) : <double>[])([root]);
}
But, as you can see, this required an additional line where the variable is defined ahead of time.
Is it possible to achieve something more similar to the python example using callable classes?
There's a classic Lisp/Scheme problem of how to create a recursive lambda. The same technique of creating one anonymous function that takes itself as an argument and then using another anonymous function to pass the first anonymous function to itself can be applied to Dart (albeit by sacrificing some type-safety; I can't think of a way to strongly type a Function that takes its own type as an argument). For example, a recursive factorial implementation:
void main() {
var factorial = (Function f, int x) {
return f(f, x);
}((Function self, int x) {
return (x <= 1) ? 1 : x * self(self, x - 1);
}, 4);
print('4! = $factorial'); // Prints: 4! = 24
}
All that said, this seems like a pretty contrived, academic problem. In practice, just create a named function. It can be a local function if you want to avoid polluting a global namespace. It would be far more readable and maintainable.
Is it possible to achieve something more similar to the python example using callable classes?
I'm not sure where you're going with that since Dart neither allows defining anonymous classes nor local classes, so even if you made a callable class, it would violate your request for being anonymous.

Obtaining numerical values from the mnewton function of the Maxima program

I use Maxima for calculations. I solve a system of nonlinear equations using Newton's method (mnewton()). I get the solution in the form of a list:
[[φ2=5.921818183272879,s=5.155870949147037]]
How to get the numerical value of the first (φ2) and second (s) unknown. If I substitute:
x: roz1[1][2]$
I get that x is equal to: s=5.155870949147037
What to do to make x equal to a numerical value only: 5.155870949147037
(without s=).
My code:
Maxima code
I have two ideas. (1) You can call rhs to return the right-hand side of an equation (likewise lhs for the left-hand side). E.g. rhs(s = 123) returns 123.
(2) You can call assoc to find the value associated with s (or any variable) in the mnewton results. E.g. assoc('s, [a = 1, b = 2, s = 3, u = 5]) returns 3.
I like (2) better since it is not necessary to know where in the list is the one that you're interested in.

Maxima: Is there any way to make functions defined within the main function be local, in a similar way to local variables?

I wonder if there is any way to make functions defined within the main function be local, in a similar way to local variables. For example, in this function that calculates the gradient of a scalar function,
grad(var,f) := block([aux],
aux : [gradient, DfDx[i]],
gradient : [],
DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
for i in [1,2,3] do (
gradient : append(gradient, [DfDx[i]])
),
return(gradient)
)$
The variable gradient that has been defined inside the main function grad(var,f) has no effect outside the main function, as it is inside the aux list. However, I have observed that the function DfDx, despite being inside the aux list, does have an effect outside the main function.
Is there any way to make the sub-functions defined inside the main function to be local only, in a similar way to what can be made with local variables? (I know that one can kill them once they have been used, but perhaps there is a more elegant way)
To address the problem you are needing to solve here, another way to compute the gradient is to say
grad(var, e) := makelist(diff(e, var1), var1, var);
and then you can say for example
grad([x, y, z], sin(x)*y/z);
to get
cos(x) y sin(x) sin(x) y
[--------, ------, - --------]
z z 2
z
(There isn't a built-in gradient function; this is an oversight.)
About local functions, bear in mind that all function definitions are global. However you can approximate a local function definition via local, which saves and restores all properties of a symbol. Since the function definition is a property, local has the effect of temporarily wiping out an existing function definition and later restoring it. In between you can create a temporary function definition. E.g.
foo(x) := 2*x;
bar(y) := block(local(foo), foo(x) := x - 1, foo(y));
bar(100); /* output is 99 */
foo(100); /* output is 200 */
However, I don't this you need to use local -- just makelist plus diff is enough to compute the gradient.
There is more to say about Maxima's scope rules, named and unnamed functions, etc. I'll try to come back to this question tomorrow.
To compute the gradient, my advice is to call makelist and diff as shown in my first answer. Let me take this opportunity to address some related topics.
I'll paste the definition of grad shown in the problem statement and use that to make some comments.
grad(var,f) := block([aux],
aux : [gradient, DfDx[i]],
gradient : [],
DfDx[i] := diff(f(x_1,x_2,x_3),var[i],1),
for i in [1,2,3] do (
gradient : append(gradient, [DfDx[i]])
),
return(gradient)
)$
(1) Maxima works mostly with expressions as opposed to functions. That's not causing a problem here, I just want to make it clear. E.g. in general one has to say diff(f(x), x) when f is a function, instead of diff(f, x), likewise integrate(f(x), ...) instead of integrate(f, ...).
(2) When gradient and Dfdx are to be the local variables, you have to name them in the list of variables for block. E.g. block([gradient, Dfdx], ...) -- Maxima won't understand block([aux], aux: ...).
(3) Note that a function defined with square brackets instead of parentheses, e.g. f[x] := ... instead of f(x) := ..., is a so-called array function in Maxima. An array function is a memoizing function, i.e. if f[x] is called two or more times, the return value is only computed once, and then returned every time thereafter. Sometimes that's a useful optimization when the domain of the function comprises a finite set.
(4) Bear in mind that x_1, x_2, x_3, are distinct symbols, not related to each other, and not related to x[1], x[2], x[3], even if they are displayed the same. My advice is to work with subscripted symbols x[i] when i is a variable.
(5) About building up return values, try to arrange to compute the whole thing at one go, instead of growing the result incrementally. In this case, makelist is preferable to for plus append.
(6) The return function in Maxima acts differently than in other programming languages; it's a little hard to explain. A function returns the value of the last expression which was evaluated, so if gradient is that last expression, you can just write grad(var, f) := block(..., gradient).
Hope this helps, I know it's obscure and complex. The Maxima programming language was not designed before being implemented, and some of the decisions are clearly questionable at the long interval of more than 50 years (!) later. That's okay, they were figuring it out as they went along. There was not a body of established results which could provide a point of reference; the original authors were contributing to what's considered common knowledge today.

Take every item in list that starts with x and put it in a new list - Rego

list := ["a:aqsdf", "a:asdf", "b:gfs", "b:sdf", "a:adfd", "b:asdfd"]
I want the new list to only include items that start with 'a': ["a:aqsdf", "a:asdf", "a:adfd"]
I've tried working with sets with no success. This would be a breeze in python but can't seem to wrap my head around rego. I can turn it into a set but not sure how to squeeze in an if statement(startswith(list[_], "a") == true)
One way to do this is with an array comprehension and the startswith builtin function:
[ x | x := list[_]; startswith(x, "a")]
Playground example: https://play.openpolicyagent.org/p/8mQYYvUL2h
This is essentially saying to define a new array containing the value of x if the rule body is true. The rule body for the comprehension is in turn iterating over all indicies of list for values of x, and will be true when the value of x starts with "a".
References:
https://www.openpolicyagent.org/docs/latest/policy-reference/#strings
https://www.openpolicyagent.org/docs/latest/policy-language/#comprehensions

What does (_,[]) mean?

I was given a question which was:
given a number N in the first argument selects only numbers greater than N in the list, so that
greater(2,[2,13,1,4,13]) = [13,4,13]
This was the solution provided:
member(_,[]) -> false;
member(H,[H|_]) -> true;
member(N,[_,T]) -> member(N,T).
I don't understand what "_" means. I understand it has something to do with pattern matching but I don't understand it completely. Could someone please explain this to me
This was the solution provided:
I think you are confused: the name of the solution function isn't even the same as the name of the function in the question. The member/2 function returns true when the first argument is an element of the list provided as the second argument, and it returns false otherwise.
I don't understand what "_" means. I understand it has something to do with pattern matching but I don't understand it completely. Could someone please explain this to me
_ is a variable name, and like any variable it will match anything. Here are some examples of pattern matching:
35> f(). %"Forget" or erase all variable bindings
ok
45> {X, Y} = {10, 20}.
{10,20}
46> X.
10
47> Y.
20
48> {X, Y} = {30, 20}.
** exception error: no match of right hand side value {30,
20}
Now why didn't line 48 match? X was already bound to 10 and Y to 20, so erlang replaces those variables with their values, which gives you:
48> {10, 20} = {30, 20}.
...and those tuples don't match.
Now lets try it with a variable named _:
49> f().
ok
50> {_, Y} = {10, 20}.
{10,20}
51> Y.
20
52> {_, Y} = {30, 20}.
{30,20}
53>
As you can see, the variable _ sort of works like the variable X, but notice that there is no error on line 52, like there was on line 48. That's because the _ variable works a little differently than X:
53> _.
* 1: variable '_' is unbound
In other words, _ is a variable name, so it will initially match anything, but unlike X, the variable _ is never bound/assigned a value, so you can use it over and over again without error to match anything.
The _ variable is also known as a don't care variable because you don't care what that variable matches because it's not important to your code, and you don't need to use its value.
Let's apply those lessons to your solution. This line:
member(N,[_,T]) -> member(N,T).
recursively calls the member function, namely member(N, T). And, the following function clause:
member(_,[]) -> false;
will match the function call member(N, T) whenever T is an empty list--no matter what the value of N is. In other words, once the given number N has not matched any element in the list, i.e. when the list is empty so there are no more elements to check, then the function clause:
member(_,[]) -> false;
will match and return false.
You could rewrite that function clause like this:
member(N, []) -> false;
but erlang will warn you that N is an unused variable in the body of the function, which is a way of saying: "Are you sure you didn't make a mistake in your function definition? You defined a variable named N, but then you didn't use it in the body of the function!" The way you tell erlang that the function definition is indeed correct is to change the variable name N to _ (or _N).
It means a variable you don't care to name. If you are never going to use a variable inside the function you can just use underscore.
% if the list is empty, it has no members
member(_, []) -> false.
% if the element I am searching for is the head of the list, it is a member
member(H,[H|_]) -> true.
% if the elem I am searching for is not the head of the list, and the list
% is not empty, lets recursively go look at the tail of the list to see if
% it is present there
member(H,[_|T]) -> member(H,T).
the above is pseudo code for what is happening. You can also have multiple '_' unnamed variables.
According to Documentation:
The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.
Example:
[H, _] = [1,2] % H will be 1
Also documentation says that:
Variables starting with underscore (_), for example, _Height, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they do not generate any warnings for unused variables.
Sorry if this is repetitive...
What does (_,[]) mean?
That means (1) two parameters, (2) the first one matches anything and everything, yet I don't care about it (you're telling Erlang to just forget about its value via the underscore) and (3) the second parameter is an empty list.
Given that Erlang binds or matches values with variables (depending on the particular case), here you're basically looking to a match (like a conditional statement) of the second parameter with an empty list. If that match happens, the statement returns false. Otherwise, it tries to match the two parameters of the function call with one of the other two statements below it.

Resources