How to specify the type signature to find a specific method with InteractiveUtils.edit in Julia? - methods

In order to quickly find the implementation of some methods I would like to use InteractiveUtils.edit.
E.g. if I wanted to see the implementation of methodswith I should be able to write something like edit(methodswith). However, as the methodswith function has multiple methods I get:
ERROR: function has multiple methods; please specify a type signature
How do I specify the type signature? I know that I can find out which methods there are with methods(methodswith), giving signatures like this:
[1] methodswith(t::Type; supertypes) in InteractiveUtils at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/InteractiveUtils/src/InteractiveUtils.jl:169
How can I plug this into a call of edit?
I know that there is #edit which I could use with some exemplary function call. However, sometimes it would be more straightforward to just specify the types, because constructing the objects for an exemplary call of the method also involves some investigation for valid constructors.
TL;DR:
How to find a specific method of a function with InteractiveUtils.edit in Julia?

Just pass argument types as a tuple in the second positional argument to edit.
For example edit(sin, (Int,)) will open you the definition of sin that is used with one argument of type Int.
Note that this might fail if you want to edit a function from stdlib (for functions from Base or non-standard libraries edit will work properly).
In such a case you have to use methods function and locate the file manually. For example:
julia> using Statistics
julia> edit(mean, (Vector{Int},)) # this might not work as expected
julia> methods(mean, (Vector{Int},))
# 1 method for generic function "mean":
[1] mean(A::AbstractArray; dims) in Statistics at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.1\Statistics\src\Statistics.jl:132
Now you have a file name and a line number where the method is located, but the path may be wrong, so you have to find the file yourself in the Julia installation folder.
Here is how you can retrieve this information programatically (assuming you have specified the args correctly and only one method matches). First define a function:
function edit_stdlib(fun, args)
m = methods(fun, args)
#assert length(m.ms) == 1 # assume we have an exact match
p = joinpath(Sys.STDLIB, splitpath(string(m.ms[1].file))[end-2:end]...)
l = m.ms[1].line
edit(p, l)
end
and now you can write e.g. edit_stdlib(mean, (Vector{Int},)) to get what you want.

Related

lua (Syntax): Calling a function that returns more than 1 value, and using those values as arguments, but without extra lines of variable assignment?

I have a situation where I need to call the following:
function xy(i)
return i,i+8
end
And use its output in another function.
function addition(x,y)
return x+y
end
Is there a way to get this to work more elegantly than writing it like:
i.e. i=10; x,y=xy(10); addition(x,y)--28
I'm looking for something like:
i.e. i=10; addition(xy(10)--where I somehow get two arguments here)
Both functions are generics used elsewhere, merging isn't viable, possible edits to what/how they return might be.
At least as of Lua 5.1, the following works 'as requested'.
When a function call is the last (or the only) argument to another call, all results from the first call go as arguments. [There are several examples using print.]
function xy(i)
return i,i+8
end
function addition(x,y)
return x+y
end
addition(xy(10)) -- 28
A more wordy way, that might be useful to decompose in similar cases needing a little bit more flexibility, is to convert the result to a table and then use unpack (added in 5.1). This approach is result -> table -> unpack -> arguments (per above).
addition(unpack({xy(10)})) -- 28
Here are both approaches in replit.

Is there a way to use a dynamic function name in Elixir from string interpolation like in Ruby?

I want to be able to construct a function call from a string in elixir. Is this possible? The equivalent ruby method call would be:
"uppercase".send("u#{:pcase}")
Although the answer by #fhdhsni is perfectly correct, I’d add some nitpicking clarification.
The exact equivalent of Kernel#send from ruby in elixir is impossible, because Kernel#send allows to call private methods on the receiver. In elixir, private functions do not ever exist in the compiled code.
If you meant Kernel#public_send, it might be achieved with Kernel.apply/3, as mentioned by #fhdhsni. The only correction is since the atom table is not garbage collected, and one surely wants to call an indeed existing function, it should be done with String.to_existing_atom/1.
apply(
String,
String.to_existing_atom("u#{:pcase}"),
["uppercase"]
)
Also, one might use macros during the compilation stage to generate respective clauses when the list of functions to call is predictable (when it’s not, the code already smells.)
defmodule Helper do
Enum.each(~w|upcase|a, fn fname ->
def unquote(fname)(param),
do: String.unquote(fname)(param)
# or
# defdelegate unquote(fname)(param), to: String
end)
end
Helper.upcase("uppercase")
#⇒ "UPPERCASE"
In Elixir module and function names are atoms. You can use apply to call them dynamically.
apply(String, String.to_atom("u#{:pcase}"), ["uppercase"]) # "UPPERCASE"
Depending on your use case it might not be a good idea to create atoms dynamically (since the atom table is not garbage collected).

Understanding Js.Promise.resolve(. ) dot syntax in ReasonML

I'm trying to understand the docs:
https://reasonml.github.io/docs/en/promise
In the usage section there is:
let myPromise = Js.Promise.make((~resolve, ~reject) => resolve(. 2));
Why is there is dot before the 2? What does it mean and what does it do?
(. ) as used here, in function application, means the function should be called with an uncurried calling convention.
When used in a function type, like the type of resolve here, (. 'a) => unit, it means the function is uncurried.
Ok, so what the hell does that mean? Wweeellll, that's a bit of a story. Here goes:
What is uncurrying?
Uncurrying is the opposite of currying, so let's explain that first and then compare.
Currying is the process of transforming a function that takes multiple arguments into a series of functions that take exactly one argument each and return either the final return value or a function taking the next argument. In Reason/OCaml this is done automatically for us, and is why in OCaml function types have arrows between its arguments (e.g. 'a -> 'b -> 'ret). You can write function types in this way in Reason too ('a => 'b => 'ret), but by default it's hidden by the syntax (('a, 'b) => 'ret), which is meant well but might also make it more difficult to understand why functions behave unexpectedly in some circumstances.
In uncurried languages supporting first-class functions you can also curry functions manually. Let's look at an example in ES6. This is a normal "uncurried" ES6 function:
let add = (a, b) => a + b;
and this is its curried form:
let add = a => b => a + b;
and with parentheses to emphasize the separate functions:
let add = a => (b => a + b);
The first function takes the argument a, then returns a function (that closes over a) which takes the argument b and then computes the final return value.
This is cool because we can easily partially apply the a argument without using bind, but it's a bit inconvenient to apply all arguments to it at once, since we have to call each function individually:
let result = add(2)(3);
So not only does Reason/OCaml automatically curry functions upon creation, but it also provides a calling convention that lets us conveniently apply multiple arguments too.
And this all works great! ...as long as every function is curried. But then we want to hang out and talk with JavaScript, where most functions are not (but see Ramda for one notable exception). To be able to call uncurried JavaScript functions we need an uncurried calling convention, and to be able to create functions that can be called as expected from JavaScript we need an uncurried function type.
Why does resolve need to be uncurried?
An even better question might be "why aren't all external functions uncurried"? The answer is that they actually are, but the type and calling convention can often both be inferred at compile-time. And if not it can often be "reflected" at runtime by inspecting the function value, at a small (but quickly compounding) cost to performance. The exceptions to this are where it gets a bit muddy, since the documentation doesn't explain exactly when explicit uncurrying is required for correct functioning, and when it isn't required but can be beneficial for performance reasons. In addition, there's actually two annotations for uncurried functions, one which can infer the calling convention and one which requires it to be explicit, as is the case here. But this is what I've gathered.
Let's look at the full signature for Js.Promise.make, which is interesting because it includes three kinds of uncurried functions:
[#bs.new]
external make :
([#bs.uncurry] (
(~resolve: (. 'a) => unit,
~reject: (. exn) => unit) => unit)) => t('a) = "Promise";
Or in OCaml syntax, which I find significantly more readable in this case:
external make : (resolve:('a -> unit [#bs]) ->
reject:(exn -> unit [#bs]) -> unit [#bs.uncurry]) -> 'a t = "Promise" [##bs.new]
The first kind of function is make itself, which is an external and can be inferred to be uncurried because all externals are of course implemented in JavaScript.
The second kind of function is the callback we'll create and pass to make. This must be uncurried because it's called from JavaScript with an uncurried calling convention. But since functions we create are curried by default, [#bs.uncurry] is used here to specify both that it expects an uncurried function, and that it should be uncurried automatically.
The third kind of function is resolve and reject, which are callback functions passed back from JavaScript and thus uncurried. But these are also 1-ary functions, where you'd think the curried and uncurried form should be exactly the same. And with ordinary monomorphic functions you'd be right, but unfortunately resolve is polymorphic, which creates some problems.
If the return type had been polymorphic, the function might actually not be 1-ary in curried form, since the return value could itself be a function taking another argument, which could return another function and so on. That's one downside of currying. But fortunately it isn't, so we know it's 1-ary.
I think the problem is even more subtle than that. It might arise because we need to be able to represent 0-ary uncurried functions using curried function types, which are all 1-ary. How do we do that? Well, if you were to implement an equivalent function in Reason/OCaml, you'd use unit as the argument type, so let's just do that. But now, if you have a polymorphic function, it might be 0-ary if it's monomorphized as unit and 1-ary otherwise. And I suppose calling a 0-ary function with one argument has been deemed unsound in some way.
But why, then, does reject need to be uncurried, when it's not polymorphic?
Well... my best guess is that it's just for consistency.
For more info, see the manual (but note that it confuses currying with partial application)

Type mismatch when calling a function in qtp

I am using QTP 11.5 for automating a web application.I am trying to call an action in qtp through driverscript as below:
RFSTestPath = "D:\vf74\D Drive\RFS Automation\"
LoadAndRunAction RFStestPath & LogInApplication,"Action1",oneIteration
Inside the LogInApplication(Action1) am calling a login function as:
Call fncLogInApplication(strURL,strUsesrName,strPasssword)
Definition of fncLogInApplication is written in fncLogInApplication.vbs
When I associate the fncLogInApplication.vbs file to driverscript, am able to execute my code without any errors. But when I de-associate .vbs file from driverscript and associate it to LogInApplication test am getting "Type mismatch: 'fncLogInApplication'"
Can anyone help me in the association please. I want fncLogInApplication to be executed when I associate to LogInApplication not to the main driverscript.
Please comment back if you require any more info
There is only one set of associated libraries that is active at any one time: That is always the outermost test's one.
This means if test A calls test B, test B will be executed with the libraries loaded based upon test A´s associated libraries list, not B's.
This also means that if B depends on a library, and B associated this library, but is called from test A (which does not associated this library), then B will fail to call (locate) the function since the associated libraries of B are never loaded (only those from A are). (As would A, naturally.).
If you are still interested: "Type mismatch" is QTPs (or VBScript´s) poor way of telling you: "The function called is not known, so I bet you instead meant an array variable dereference, and the variable you specified is equal to empty, so it is not an array, and thus cannot be dereferenced as an array variable, which is what I call a 'type mismatch'."
This reasoning is valid, considering the syntax tree of VB/VBScript: Function calls and array variable dereferences cannot be formally differentiated. Syntactically, they are very similar, or identical in most cases. So be prepared to handle "Type mismatch" like the "Unknown function referenced" message that VB/VBScript never display when creating VBScript code.
You can, however, load the library you want in test B´s code (for example, using LoadFunctionLibrary), but this still allows A to call functions from that library once B loaded it and returned from A´s call. This, and all the possible variations of this procedure, however, have side-effects to aspects like debugging, forward references and visibility of global variables, so I would recommend against it.
Additional notes:
There is no good reason to use CALL. Just call the sub or function.
If you call a function and use the result it returns, you must include the arguments in parantheses.
If you call a sub (or a function, and don´t use the result it returns), you must not include the arguments in parantheses. If the sub or function accepts only one argument, it might look like you are allowed to put it in parantheses, but this is not true. In this case, the argument is simply treated like a term in parantheses.
The argument "bracketing" aspects just listed can create very nasty bugs, especially if the argument is byRef, also due (but not limited) to the fact that VBScripts unfortunately allows you to pass values for a byRef argument (where a variable parameter is expected), so it is generally a good idea to put paranthesis only where it belongs (i.e. where absolutely needed).

scala coalesces multiple function call parameters into a Tuple -- can this be disabled?

This is a troublesome violation of type safety in my project, so I'm looking for a way to disable it. It seems that if a function takes an AnyRef (or a java.lang.Object), you can call the function with any combination of parameters, and Scala will coalesce the parameters into a Tuple object and invoke the function.
In my case the function isn't expecting a Tuple, and fails at runtime. I would expect this situation to be caught at compile time.
object WhyTuple {
def main(args: Array[String]): Unit = {
fooIt("foo", "bar")
}
def fooIt(o: AnyRef) {
println(o.toString)
}
}
Output:
(foo,bar)
No implicits or Predef at play here at all -- just good old fashioned compiler magic. You can find it in the type checker. I can't locate it in the spec right now.
If you're motivated enough, you could add a -X option to the compiler prevent this.
Alternatively, you could avoid writing arity-1 methods that accept a supertype of TupleN.
What about something like this:
object Qx2 {
#deprecated def callingWithATupleProducesAWarning(a: Product) = 2
def callingWithATupleProducesAWarning(a: Any) = 3
}
Tuples have the Product trait, so any call to callingWithATupleProducesAWarning that passes a tuple will produce a deprecation warning.
Edit: According to people better informed than me, the following answer is actually wrong: see this answer. Thanks Aaron Novstrup for pointing this out.
This is actually a quirk of the parser, not of the type system or the compiler. Scala allows zero- or one-arg functions to be invoked without parentheses, but not functions with more than one argument. So as Fred Haslam says, what you've written isn't an invocation with two arguments, it's an invocation with one tuple-valued argument. However, if the method did take two arguments, the invocation would be a two-arg invocation. It seems like the meaning of the code affects how it parses (which is a bit suckful).
As for what you can actually do about this, that's tricky. If the method really did require two arguments, this problem would go away (i.e. if someone then mistakenly tried to call it with one argument or with three, they'd get a compile error as you expect). Don't suppose there's some extra parameter you've been putting off adding to that method? :)
The compile is capable of interpreting methods without round brackets. So it takes the round brackets in the fooIt to mean Tuple. Your call is the same as:
fooIt( ("foo","bar") )
That being said, you can cause the method to exclude the call, and retrieve the value if you use some wrapper like Some(AnyRef) or Tuple1(AnyRef).
I think the definition of (x, y) in Predef is responsible. The "-Yno-predefs" compiler flag might be of some use, assuming you're willing to do the work of manually importing any implicits you otherwise need. By that I mean that you'll have to add import scala.Predef._ all over the place.
Could you also add a two-param override, which would prevent the compiler applying the syntactic sugar? By making the types taking suitably obscure you're unlikely to get false positives. E.g:
object WhyTuple {
...
class DummyType
def fooIt(a: DummyType, b: DummyType) {
throw new UnsupportedOperationException("Dummy function - should not be called")
}
}

Resources