Mathematica 9 - function definition problems - function

Please excuse the beginner question. I couldn't find an appropriate answer in any Mathematica tutorial.
I am confused why a definition as a function or a definition in terms of a simple replacement produce different results. Consider this example (Mathematica 9 code):
In[397]:= ClearAll["Global`*"]
In[398]:= Test := 3 c^2 + d^4
In[399]:= v[f_] := D[f, c]
In[400]:= v[Test]
Out[400]= 6 c
The first definition of this simple derivative function "v" acting on a variable is fine. Defining a replacement Test = ... to replace the variable produces the expected result (It derives 3c^2+d^4 with respect to c and answers 6c).
However if I define a function instead of a simple replacement this does not work:
In[401]:= TestFunction[a_, b_] := 3 a^2 + b^4
In[403]:= vFunction[f_[a_, b_]] := D[f[a, b], a]
In[405]:= vFunction[TestFunction[a, b]]
Out[405]= \!\(
\*SubscriptBox[\(\[PartialD]\), \(3\
\*SuperscriptBox[\(a\), \(2\)]\)]\((3\
\*SuperscriptBox[\(a\), \(2\)] +
\*SuperscriptBox[\(b\), \(4\)])\)\)
Why is that? I am risking to look like a moron here, but please enlighten me!
For your convenience, I uploaded a copy of my workbook here
Thanks a lot,
Michael

Do this instead
vFunction[f_,a_,b_]:=D[f[a,b],a];
and when you need derivatives simply use vFunction[TestFunction,a,b] to get it.
When you write down f[x], it means the evaluated value of f with argument value x. So, f[x] is technically not a function anymore. What you want as the argument of vFunction[] is the function TestFunction, not the evaluated value.

Related

Use of function / return

I had the task to code the following:
Take a list of integers and returns the value of these numbers added up, but only if they are odd.
Example input: [1,5,3,2]
Output: 9
I did the code below and it worked perfectly.
numbers = [1,5,3,2]
print(numbers)
add_up_the_odds = []
for number in numbers:
if number % 2 == 1:
add_up_the_odds.append(number)
print(add_up_the_odds)
print(sum(add_up_the_odds))
Then I tried to re-code it using function definition / return:
def add_up_the_odds(numbers):
odds = []
for number in range(1,len(numbers)):
if number % 2 == 1:
odds.append(number)
return odds
numbers = [1,5,3,2]
print (sum(odds))
But I couldn’t make it working, anybody can help with that?
Note: I'm going to assume Python 3.x
It looks like you're defining your function, but never calling it.
When the interpreter finishes going through your function definition, the function is now there for you to use - but it never actually executes until you tell it to.
Between the last two lines in your code, you need to call add_up_the_odds() on your numbers array, and assign the result to the odds variable.
i.e. odds = add_up_the_odds(numbers)

value of a function that takes an argument which is itself a function

I am trying a simple function as follows:
function out=Y_T(f,a,b)
Y_T=f(a)-f(b)
end
f is an argument which is a function itself. For example f=x^4+3. The function T_Y should evaluate the values of f in 'a' and 'b' and subtract them. But when i try to use this function for example T_Y(x^4+3,5,2) i face with an error: Index exceeds matrix dimension. How can i fix it? Any tips will be appreciated.
Thanks a lot.
I think you simply have your syntax wrong - as written, you're passing the numeric value x^4 + 3 into Y_T. I think what you need is:
Y_T(#(x) x^4 + 3, 5, 2)
This defines an anonymous function, and passes it in to Y_T.
Your definition of Y_T is slightly wrong too - you need to assign the result to out, like so:
function out=Y_T(f,a,b)
out=f(a)-f(b)
end

SML Issue with a function creating another function

Keep in mind, this is part of a homework assignment - so please, no direct answer. I just need some help in finding out the answer, so a link to a tutorial to help me understand the material would be great.
SML code:
datatype 'ingredient pizza =
Bottom
| Topping of ('ingredient * ('ingredient pizza));
datatype fish =
Anchovy
| Shark
| Tuna;
(* Testing Pizza Objects *)
val my_pizza1 = Topping(Tuna, Topping(Shark, Topping(Anchovy, Bottom)));
val my_pizza2 = Topping(Shark, Topping(Tuna, Topping(Anchovy, Bottom)));
val my_pizza3 = Topping(Anchovy, Topping(Shark, Topping(Tuna, Bottom)));
(* My Function Start *)
fun rem_ingredient Bottom = Bottom
| rem_ingredient(t) = fn(Topping(p)) => Topping(t, rem_ingredient(p))
| rem_ingredient(Topping(t,p)) = Topping(t, rem_ingredient(p));
(* My Function End *)
If I call the function rem_ingredient with 1 parameter
val rem_tuna = rem_ingredient Tuna;"
I should get a function that can then call
rem_tuna my_pizza3;
to remove Tuna from pizza3
If I call the same function with 2 parameters
rem_ingredient Tuna my_pizza2;
I should directly remove Tuna from the pizza2 object with the 2 parameters.
The Problem:
I keep getting the error: syntax error: replacing EQUALOP with DARROW on the 3rd constructor of rem_ingredient, I know I'm missing something that is probably obvious. We just start learning SML last week in Programming Languages and I'm still trying to understand it. Anyone pointing me in direction would be appreciated.
Again, no direct answer please, I want to learn the material, but I'm not sure what I'm trying to fix.
To get rid of the syntax error you need to put parentheses around the fn expression (since the following | pattern is otherwise taken to be part of the fn).
However, that is not your real problem here. The function as written does not have a consistent type, because the second case returns a function while the others do not.

Lua - How do I use a function from another script?

I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.

Error generating localized variables (as constants)

The usage message for Set reminds us that multiple assignments can easily be made across two lists, without having to rip anything apart. For example:
Remove[x1, x2, y1, y2, z1, z2];
{x1, x2} = {a, b}
Performs the assignment and returns:
{a, b}
Thread, commonly used to generate lists of rules, can also be called explicitly to achieve the same outcome:
Thread[{y1, y2} = {a, b}]
Thread[{z1, z2} -> {a, b}]
Gives:
{a, b}
{z1 -> a, z2 -> b}
However, employing this approach to generate localized constants generates an error. Consider this trivial example function:
Remove[f];
f[x_] :=
With[{{x1, x2} = {a, b}},
x + x1 + x2
]
f[z]
Here the error message:
With::lvset: "Local variable specification {{x1,x2}={a,b}} contains
{x1,x2}={a,b}, which is an assignment to {x1,x2}; only assignments
to symbols are allowed."
The error message documentation (ref/message/With/lvw), says in the 'More Information' section that, "This message is generated when the first element in With is not a list of assignments to symbols." Given this explanation, I understand the mechanics of why my assignment failed. Nonetheless, I'm puzzled and wondering if this is necessary restriction by WRI, or a minor design oversight that should be reported.
So here's my question:
Can anyone shed some light on this behavior and/or offer a workaround? I experimented with trying to force Evaluation, without luck, and I'm not sure what else to try.
What you request is tricky. This is a job for macros, as already exposed by the others. I will explore a different possibility - to use the same symbols but put some wrappers around the code you want to write. The advantage of this technique is that the code is transformed "lexically" and at "compile-time", rather than at run-time (as in the other answers). This is generally both faster and easier to debug.
So, here is a function which would transform the With with your proposed syntax:
Clear[expandWith];
expandWith[heldCode_Hold] :=
Module[{with},
heldCode /. With -> with //. {
HoldPattern[with[{{} = {}, rest___}, body_]] :>
with[{rest}, body],
HoldPattern[
with[{
Set[{var_Symbol, otherVars___Symbol}, {val_, otherVals___}], rest___},
body_]] :>
with[{{otherVars} = {otherVals}, var = val, rest}, body]
} /. with -> With]
Note that this operates on held code. This has the advantage that we don't have to worry about possible evaluation o the code neither at the start nor when expandWith is finished. Here is how it works:
In[46]:= expandWith#Hold[With[{{x1,x2,x3}={a,b,c}},x+x1+x2+x3]]
Out[46]= Hold[With[{x3=c,x2=b,x1=a},x+x1+x2+x3]]
This is, however, not very convenient to use. Here is a convenience function to simplify this:
ew = Function[code, ReleaseHold#expandWith#Hold#code, HoldAll]
We can use it now as:
In[47]:= ew#With[{{x1,x2}={a,b}},x+x1+x2]
Out[47]= a+b+x
So, to make the expansion happen in the code, simply wrap ew around it. Here is your case for the function's definition:
Remove[f];
ew[f[x_] := With[{{x1, x2} = {a, b}}, x + x1 + x2]]
We now check and see that what we get is an expanded definition:
?f
Global`f
f[x_]:=With[{x2=b,x1=a},x+x1+x2]
The advantage of this approach is that you can wrap ew around an arbitrarily large chunk of your code. What happens is that first, expanded code is generated from it, as if you would write it yourself, and then that code gets executed. For the case of function's definitions, like f above, we cansay that the code generation happens at "compile-time", so you avoid any run-time overhead when usin the function later, which may be substantial if the function is called often.
Another advantage of this approach is its composability: you can come up with many syntax extensions, and for each of them write a function similar to ew. Then, provided that these custom code-transforming functions don't conlict with each other, you can simply compose (nest) them, to get a cumulative effect. In a sense, in this way you create a custom code generator which generates valid Mathematica code from some Mathematica expressions representing programs in your custom languuage, that you may create within Mathematica using these means.
EDIT
In writing expandWith, I used iterative rule application to avoid dealing with evaluation control, which can be a mess. However, for those interested, here is a version which does some explicit work with unevaluated pieces of code.
Clear[expandWithAlt];
expandWithAlt[heldCode_Hold] :=
Module[{myHold},
SetAttributes[myHold, HoldAll];
heldCode //. HoldPattern[With[{Set[{vars__}, {vals__}]}, body_]] :>
With[{eval =
(Thread[Unevaluated[Hold[vars] = Hold[vals]], Hold] /.
Hold[decl___] :> myHold[With[{decl}, body]])},
eval /; True] //. myHold[x_] :> x]
I find it considerably more complicated than the first one though.
The tricky issue is to keep the first argument of Set unevaluated.
Here is my suggestion (open to improvements of course):
SetAttributes[myWith, HoldAll];
myWith[{s : Set[a_List, b_List]}, body_] :=
ReleaseHold#
Hold[With][
Table[Hold[Set][Extract[Hold[s], {1, 1, i}, Hold],
Extract[Hold[s], {1, 2, i}]], {i, Length#b}], Hold#body]
x1 = 12;
Remove[f];
f[x_] := myWith[{{x1, x2} = {a, b}}, x + x1 + x2]
f[z]
results in
a+b+z
Inspired by halirutan below I think his solution, made slightly more safely, is equivalent to the above:
SetAttributes[myWith, HoldAll];
myWith[{Set[a : {__Symbol}, b_List]} /; Length[a] == Length[b],
body_] :=
ReleaseHold#
Hold[With][
Replace[Thread[Hold[a, b]], Hold[x_, y_] :> Hold[Set[x, y]], 1],
Hold#body]
The tutorial "LocalConstants" says
The way With[{x=Subscript[x, 0],...},body] works is to take body, and replace every
occurrence of x, etc. in it by Subscript[x, 0], etc. You can think of With as a
generalization of the /. operator, suitable for application to Mathematica code instead of
other expressions.
Referring to this explanation it seems obvious that something like
x + x1 + x2 /. {x1, x2} -> {a, b}
will not work as it might be expected in the With notation.
Let's assume you really want to hack around this. With[] has the attribute HoldAll, therefore everything you give as first parameter is not evaluated. To make such a vector-assignment work you would have to create
With[{x1=a, x2=b}, ...]
from the vector-notation. Unfortunately,
Thread[{a, b} = {1, 2}]
does not work because the argument to Thread is not held and the assignment is evaluated before Thread can do anything.
Lets fix this
SetAttributes[myThread, HoldFirst];
myThread[Set[a_, b_]] := mySet ### Transpose[{a, b}]
gives
In[31]:= myThread[{a, b, c} = {1, 2, 3}]
Out[31]= {mySet[a, 1], mySet[b, 2], mySet[c, 3]}
What looks promising at first, just moved the problem a bit away. To use this in With[] you have to replace at some point the mySet with the real Set. Exactly then, With[] does not see the list {a=1, b=2, c=3} but, since it has to be evaluated, the result of all assignments
In[32]:= With[
Evaluate[myThread[{a, b, c} = {1, 2, 3}] /. mySet :> Set], a + b + c]
During evaluation of In[32]:= With::lvw: Local
variable specification {1,2,3} contains 1, which is not an assignment to a symbol. >>
Out[32]= With[{1, 2, 3}, a + b + c]
There seems to be not easy way around this and there is a second question here: If there is a way around this restriction, is it as fast as With would be or do we lose the speed advantage compared to Module? And if speed is not so important, why not using Module or Block in the first place?
You could use Transpose to shorten Rolfs solution by 100 characters:
SetAttributes[myWith, HoldAll];
myWith[{Set[a_List, b_List]}, body_] :=
ReleaseHold[Hold[With][Hold[Set[#1, #2]] & ### Transpose[{a, b}],
Hold#body
]]
#Heike, yep the above breaks if either variable has already a value. What about this:
SetAttributes[myWith, HoldAll];
myWith[{Set[a_List, b_List]}, body_] :=
ReleaseHold#
Hold[With][Thread[Hold[a, b]] /. Hold[p__] :> Hold[Set[p]],
Hold#body]