Retrieve method content as an `Expr`ession - expression

I have a function f defined as follows.
f(x, y) = 3x^2 + x*y - 2y + 1
How can I retrieve the following quote block for this method, which includes the function contents?
quote # REPL[0], line 2:
((3 * x ^ 2 + x * y) - 2y) + 1
end

As folks have mentioned in the comments, digging through the fields of the methods like this isn't a stable or officially supported API. Further, your simple example is deceiving. This isn't, in general, representative of the original code you wrote for the method. It's a simplified intermediate AST representation with single-assignment variables and drastically simplified control flow. In general, the AST it returns isn't valid top-level Julia code. It just so happens that for your simple example, it is.
That said, there is a documented way to do this. You can use code_lowered() to get access to this intermediate representation without digging through undocumented fields. This will work across Julia versions, but I don't think there are official guarantees on the stability of the intermediate representation yet. Here's a slightly more complicated example:
julia> f(X) = for elt in X; println(elt); end
f (generic function with 1 method)
julia> code_lowered(f)[1]
LambdaInfo template for f(X) at REPL[17]:1
:(begin
nothing
SSAValue(0) = X
#temp# = (Base.start)(SSAValue(0))
4:
unless !((Base.done)(SSAValue(0),#temp#)) goto 13
SSAValue(1) = (Base.next)(SSAValue(0),#temp#)
elt = (Core.getfield)(SSAValue(1),1)
#temp# = (Core.getfield)(SSAValue(1),2) # line 1:
(Main.println)(elt)
11:
goto 4
13:
return
end)
julia> code_lowered(f)[1] == methods(f).ms[1].lambda_template
true
If you really want to see the code exactly as it was written, the best way is to use the embedded file and line information and refer to the original source. Note that this is precisely the manner in which Gallium.jl (Julia's debugger) finds the source to display as it steps through functions. It's undocumented, but you can even access the REPL history for functions defined interactively. See how Gallium does it through here.

First, retrieve the method using methods(f).
julia> methods(f)
# 1 method for generic function "f":
f(x, y) at REPL[1]:1
julia> methods(f).ms
1-element Array{Method,1}:
f(x, y) at REPL[1]:1
julia> method = methods(f).ms[1]
f(x, y) at REPL[1]:1
From here, retrieving the Expression is straightforward; simply use the lambda_template attribute of the method.
julia> method.lambda_template
LambdaInfo template for f(x, y) at REPL[1]:1
:(begin
nothing
return ((3 * x ^ 2 + x * y) - 2 * y) + 1
end)
Edit: This does not work in Julia v0.6+!

Related

What is the correct function definition syntax in CoffeeScript?

On the official CoffeeScript website the syntax for defining a function is
square = (x) -> x * x
However, on some other websites I found out that the syntax could also be
square: (x) -> x * x
Is one of the options preferred?
There is a huge difference between those two options. Firstly, they have nothing to do with function syntax, which is always (x) -> x * x. They only differs in what you are doing with the function.
The first option defines a local variable square and assign that function to it. hence afterwards you can simply call square(2) to get 4.
Second option is creating a javascript object. If this is the last line of some function, this is its return value. Object has to be assigned to some variable, otherwise it is lost:
functions =
square: (x) -> x * x
functions.square(2)

Differentiate an infix formal language functions

I have a source file like (without loss of generality (only to image a possible syntax)):
function a()
return g // global variable without any internal structure exactly
end
function b(x, y)
local z = x * y
return z + 1
end
function c(z, t)
return b(z * z, a())
end
// ...etc
I want to defferentiate any function WRT to some variable.
All the formal parametres we can treat as a functions with unknown at derive time internal structure.
If I stand correct further, then the following is truth (for depending symbols ' is part of symbol, for global variables is operator during substitute time stage (def: g{g} is one, but g{y} is zero)):
function a'()
return g';
end
function b'(x, y, x', y')
local z' = x' * y + x * y'
return z' + 0
end
But what to do with last function? Namely, with actual parameters in substitution of function b?
Is there any ready to use implementations of general algorithm to work with the above? What to do with higher order derivatives (especially interesting, how to handle the formal parameters)? Are there any other possible unclear cases?
I would suggest having your parameters be symbolic expressions that know how to respond to derivatives, and having all operations take functions and return functions. Then you will get a final expression that knows how to be represented as a derivative. Furthermore you can do things like partial derivatives at a later point because you have the symbolic expression.
For a real example of what I mean, see http://www.elem.com/~btilly/kelly-criterion/js/advanced-math.js for a library that I wrote to solve a calculus problem in JavaScript, and search for "Optimize if requested" in the source for http://www.elem.com/~btilly/kelly-criterion/betting-returns2.html to see how I used it. See http://www.elem.com/~btilly/kelly-criterion/ for an explanation of why I was writing that code.
In that example I, of course, was not working from infix notation. But that is a standard parsing problem that I think you know how to solve.

Julia: Passing Multiple Arguments to Anonymous Functions

In the Julia Manual under the Anonymous Functions section one of the examples that is offered is (x,y,z)->2x+y-z.
Could someone please show me how one would pass a set of arguments to this function?
Say x=(1,2,3); y=(2,3,4); z=(1,3,5).
If you define x,y and z to be arrays then you can just call the function and pass them in:
fun = (x,y,z)->2x+y-z
x=[1,2,3]
y=[2,3,4]
z=[1,3,5]
fun(x, y, z)
giving the result:
3-element Array{Int64,1}:
3
4
5
But if you want to do this with tuples, as per your example, you will need to use map:
x=(1,2,3)
y=(2,3,4)
z=(1,3,5)
map(fun, x, y, z)
this gives the same result, but this time as a tuple:
(3, 4, 5)
This is because the *, + and - operators are not defined for tuples so the formula 2x+y-z can't work. Using map gets around this by calling the function multiple times passing in scalars.
You have to assign the anonymous function to a variable, in order to call it.
julia> fun = (x,y,z)->2x+y-z
(anonymous function)
julia> fun((1,2,3),(2,3,4),(1,3,5))
ERROR: no method *(Int64, (Int64,Int64,Int64))
in anonymous at none:1
It does not work, because the tuples you set for x, does not implement the * function.

Functional programming languages with methods, method chaining etc

I've been investigating functional programming, and it occurred to me that there could be a functional language which has (immutable) objects with methods, and which therefore supports method chaining (where chainable methods would return new instances rather than mutating the instance the method is called on and returning it).
This would have readability advantages as...
o.f().g().h()
... is arguably more readable than:
h(g(f(o)))
It would also allow you to associate particular functions with particular types of object, by making them methods of those types (which I understand to be one advantage of object-oriented langauges).
Are there any languages which behave like this? Are there any reasons to believe that this would be a bad idea?
(I know that you can program like this in e.g Javascript, but Javascript doesn't enforce immutability.)
yes, for example, F# uses the forward pipe (|>) operator which makes the code very readable. for example,
(1..20)
|> Seq.map(functionFoo)
|> Seq.map(functionBoo)
and so on...
Frege has this, it is known as TDNR (type directed name resolution).
Specifically, if x has type T, and y occurs in the namespace of T, then x.y is the same as (T.y x) which is in plain english y from the name space T applied to x.
Practical applications of this are: convenient syntax for record field access and access to native (i.e. Java, as Frege is compiled to Java) methods.
Scala sounds like a good fit - it's a hybrid functional / object-oriented language.
You don't need objects for that, just define your own reverse apply infix operator, which most functional languages allow you to do. Currying then does the rest. For example, in OCaml:
let (>>) x f = f x
Demo:
let f x y z = z * (x - y)
let g x = x + 1
let h x y = y * x
5 >> f 6 2 >> g >> h 2 (* = h 2 (g (f 6 2 5)) *)
(Or choose whatever operator name you prefer; others use |> for example.)

Obtain x as result for Re[x] in mathematica

I'm trying to obtain the real part of the result of an operation which involves an undefined variable (let's say x).
How can I have Mathematica return x when I execute Re[x] if I know that x will never be a complex number? I think this involves telling Mathematica that x is a real, but I don't know how.
In my case the expression for which I want the real part is more complicated than a simple variable, but the concept will remain the same.
Some examples:
INPUT OUTPUT DESIRED RESULT
----- ------ --------------
Re[x] Re[x] x
Re[1] 1 1
Re[Sin[x]] Re[Sin[x]] Sin[x]
Re[1+x+I] 1 + Re[x] 1+x
Re[1 + x*I] 1-Im[x] 1
You can use for example the input Simplify[Re[x], x \[Element] Reals] which will give x as output.
Use ComplexExpand. It assumes that the variables are real unless you indicate otherwise. For example:
In[76]:= ComplexExpand[Re[x]]
Out[76]= x
In[77]:= ComplexExpand[Re[Sin[x]]]
Out[77]= Sin[x]
In[78]:= ComplexExpand[Re[1+x+I]]
Out[78]= 1+x
Two more possibilities:
Assuming[x \[Element] Reals, Refine[Re[x]]]
Refine[Re[x], x \[Element] Reals]
Both return x.
It can at times be useful to define UpValues for a symbol. This is far from robust, but it nevertheless can handle a number of cases.
Re[x] ^= x;
Im[x] ^= 0;
Re[x]
Re[1]
Re[1 + x + I]
Re[1 + x*I]
x
1
1 + x
1
Re[Sin[x]] does not evaluate as you desire, but one of the transformations used by FullSimplify does place it in a form that triggers Re[x]:
Re[Sin[x]] // FullSimplify
Sin[x]

Resources