I would like to print the function definition of any nested function when printing the definition of the outer function. Example:
g:{sin x}
f:{cos g x}
When I print f I get {cos g x} but I want to get {cos {sin x} x}
Thanks for the help
From what I am aware it is not possible to achieve that with in-build functions.
You can attempt to write your own function that does that but it will be a pain in the end. Something like this maybe:
q)m:string[v]!string value each v:value[f][3] except `
which creates a dictionary m :
q)m
,"g"| "{sin x}"
When given a function value returns a list containing (bytecode;parameters;locals(context;globals);constants[0];...;constants[n];definition)
However, if we pass a symbol to value it returns the value of that symbol (or function definition in this case).
You can then use ssr to replace the functions in f with the function definitions stored in your dictionary m.
q)ssr/[last value[f];key m;value m]
"{cos {sin x} x}"
but to ensure that your function is stable and adaptable to different functions would be very difficult.
For more details about how value have a look here: https://code.kx.com/q/ref/metadata/#value
For ssr check this link:
https://code.kx.com/q/ref/strings/#ssr
Related
I am having a couple of issues to put this in a functional format.
select from tableName where i=fby[(last;i);([]column_one;column_two)]
This is what I got:
?[tableName;fby;enlist(=;`i;(enlist;last;`i);(+:;(!;enlist`column_one`column_two;(enlist;`column_one;`column_two))));0b;()]
but I get a type error.
Any suggestions?
Consider using the following function, adjust from the buildQuery function given in the whitepaper on Parse Trees. This is a pretty useful tool for quickly developing in q, this version is an improvement on that given in the linked whitepaper, having been extended to handle updates by reference (i.e., update x:3 from `tab)
\c 30 200
tidy:{ssr/[;("\"~~";"~~\"");("";"")] $[","=first x;1_x;x]};
strBrk:{y,(";" sv x),z};
//replace k representation with equivalent q keyword
kreplace:{[x] $[`=qval:.q?x;x;"~~",string[qval],"~~"]};
funcK:{$[0=t:type x;.z.s each x;t<100h;x;kreplace x]};
//replace eg ,`FD`ABC`DEF with "enlist`FD`ABC`DEF"
ereplace:{"~~enlist",(.Q.s1 first x),"~~"};
ereptest:{((0=type x) & (1=count x) & (11=type first x)) | ((11=type x)&(1=count x))};
funcEn:{$[ereptest x;ereplace x;0=type x;.z.s each x;x]};
basic:{tidy .Q.s1 funcK funcEn x};
addbraks:{"(",x,")"};
//where clause needs to be a list of where clauses, so if only one whereclause need to enlist.
stringify:{$[(0=type x) & 1=count x;"enlist ";""],basic x};
//if a dictionary apply to both, keys and values
ab:{$[(0=count x) | -1=type x;.Q.s1 x;99=type x;(addbraks stringify key x),"!",stringify value x;stringify x]};
inner:{[x]
idxs:2 3 4 5 6 inter ainds:til count x;
x:#[x;idxs;'[ab;eval]];
if[6 in idxs;x[6]:ssr/[;("hopen";"hclose");("iasc";"idesc")] x[6]];
//for select statements within select statements
//This line has been adjusted
x[1]:$[-11=type x 1;x 1;$[11h=type x 1;[idxs,:1;"`",string first x 1];[idxs,:1;.z.s x 1]]];
x:#[x;ainds except idxs;string];
x[0],strBrk[1_x;"[";"]"]
};
buildSelect:{[x]
inner parse x
};
We can use this to create the functional query that will work
q)n:1000
q)tab:([]sym:n?`3;col1:n?100.0;col2:n?10.0)
q)buildSelect "select from tab where i=fby[(last;i);([]col1;col2)]"
"?[tab;enlist (=;`i;(fby;(enlist;last;`i);(flip;(lsq;enlist`col1`col2;(enlist;`col1;`col2)))));0b;()]"
So we have the following as the functional form
?[tab;enlist (=;`i;(fby;(enlist;last;`i);(flip;(lsq;enlist`col1`col2;(enlist;`col1;`col2)))));0b;()]
// Applying this
q)?[tab;enlist (=;`i;(fby;(enlist;last;`i);(flip;(lsq;enlist`col1`col2;(enlist;`col1;`col2)))));0b;()]
sym col1 col2
----------------------
bah 18.70281 3.927524
jjb 35.95293 5.170911
ihm 48.09078 5.159796
...
Glad you were able to fix your problem with converting your query to functional form.
Generally it is the case that when you use parse with a fby in your statement, q will convert this function into its k definition. Usually you should just be able to replace this k code with the q function itself (i.e. change (k){stuff} to fby) and this should run properly when turning the query into functional form.
Additionally, if you check out https://code.kx.com/v2/wp/parse-trees/ it goes into more detail about parse trees and functional form. Additionally, it contains a script called buildQuery which will return the functional form of the query of interest as a string which can be quite handy and save time when a functional form is complex.
I actually got it myself ->
?[tableName;((=;`i;(fby;(enlist;last;`i);(+:;(!;enlist`column_one`column_two;(enlist;`column_one;`column_two)))));(in;`venue;enlist`venueone`venuetwo));0b;()]
The issues was a () missing from the statement. Works fine now.
**if someone wants to add a more detailed explanation on how manual parse trees are built and how the generic (k){} function can be replaced with the actual function in q feel free to add your answer and I'll accept and upvote it
I want to be able to find the parameter names of an anonymous function in Matlab.
I tried to see if there was any information about the parameter names in the functions() command, but to no avail.
Say I have an anonymous function f:
f = #(x, y) x^2 + y^2
I need to be able to find the parameter names 'x' and 'y' from this equation. Is there a built in method in Matlab which can do this? Or would I somehow have to parse the function to receive the parameter names?
The function field in the output of functions (or equivalently the output of func2str) gives the function definition as a string. You then use a regular expression to match each sequence of one or more non-), non-, characters that are between a #( or , and a , or ):
s = functions(f);
inputVarNames = regexp(s.function, '(?<=(,|#\())[^\)]+?(?=(,|\)))', 'match');
I have a function
f:{[t;c];
q: (1.0;0.8;0.6;0.4;0.2);
tc:(cols[t] where cols[t] like c)[0];
sorted:desc t[tc];
qt:( {x: "i"$sorted["i"$x*count sorted]} each q) ! q;
k:asc key qt;
{[t;c;n;f] #[t;n;:;f t c]}[t;c;`quint;{[x] qt k k binr "i"$x}]
}
when I try to call it, it returns ERROR:sorted. It seems the variables declared inside the function are not accessible in {x: "i"$sorted["i"$x*count sorted]}. However, if I declare them outside the function then they are accessible (and I can call the function successfully). Is there a way to make them available to the {...}?
To access sorted you can pass it in as a argument to the function.
{"i"$x["i"$y*count x]}[sorted]each q
Same applies to the second lambda and on the last line too, again passing the arguments qt and k to it:
{x y y binr "i"$z}[qt;k]
I'm pretty new on Julia and have a question that may appear simple. Say I have a function, which I will name test(x::Vector, arg1, arg2) where x is a vector of variables and the function has two arguments arg1 & arg2.
I would like to optimize (minimize) the function test with respect to the vector x. I can't figure out how to use the optimize function from the Optim package that accepts two arguments values. In R, one may do as following:
optim(initial guest, test, arg1=value1,arg2=value2)
Is there a similar way to declare argument value in Julia?
You can define another function that fixes the value of those arguments.
# Function to minimize
f(x::Vector, a, b) = (x[1] - a)^2 + (x[2] - b)^2
using Optim
g(x::Vector) = f(x, 3, 4)
optimize(g, [0.,0.])
You could also use an anonymous function (but it may be less efficient).
optimize(x -> f(x,3,4), [0.,0.])
I wrote a code that finds the root of a function whose name is provided among the arguments, I think I took it from Numerical Recipes. Something like
double precision function rtsafe(x_init, x1, x2, xacc, func, dfunc)
where func and dfunc are two functions' names.
Of course I use rtsafe with different function func and dfunc.
I would like to print the name of the called functions func and dfunc when I am inside rtsafe, because when there is an error in rtsafe I would like to know which function I was using. Something like
write(,)"my func = ", func
(?)
Does anybody know how to do that?
You could add an optional argument in your functions that returns the name of the function:
FUNCTION f(x, fname) RESULT (fx)
IMPLICIT NONE
REAL :: x, fx
CHARACTER(LEN=*), OPTIONAL :: fname
CHARACTER(LEN=*), PARAMETER :: myfname='somename'
IF (present(fname)) fname=myfname
fx = x ! or whatever else
END FUNCTION f
In the first call to your function in rtsafe you get the name of the function for later printing in case of an error.
Did not test this but it should work more or less like this, and it the only way I can think of to do this in Fortran.
Maybe you can work up some manual solution (pass the name of the function, then print it with "OK" ... or something like that), but printing the names of the functions/subroutines (reflecting) is not possible.