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

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.

Related

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).

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

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.

Mathematica - can I define a block of code using a single variable?

It has been a while since I've used Mathematica, and I looked all throughout the help menu. I think one problem I'm having is that I do not know what exactly to look up. I have a block of code, with things like appending lists and doing basic math, that I want to define as a single variable.
My goal is to loop through a sequence and when needed I wanted to call a block of code that I will be using several times throughout the loop. I am guessing I should just put it all in a loop anyway, but I would like to be able to define it all as one function.
It seems like this should be an easy and straightforward procedure. Am I missing something simple?
This is the basic format for a function definition in Mathematica.
myFunc[par1_,par2_]:=Module[{localVar1,localVar2},
statement1; statement2; returnStatement ]
Your question is not entirely clear, but I interpret that you want something like this:
facRand[] :=
({b, x} = Last#FactorInteger[RandomInteger[1*^12]]; Print[b])
Now every time facRand[] is called a new random integer is factored, global variables b and x are assigned, and the value of b is printed. This could also be done with Function:
Clear[facRand]
facRand =
({b, x} = Last#FactorInteger[RandomInteger[1*^12]]; Print[b]) &
This is also called with facRand[]. This form is standard, and allows addressing or passing the symbol facRand without triggering evaluation.

Any reason NOT to always use keyword arguments?

Before jumping into python, I had started with some Objective-C / Cocoa books. As I recall, most functions required keyword arguments to be explicitly stated. Until recently I forgot all about this, and just used positional arguments in Python. But lately, I've ran into a few bugs which resulted from improper positions - sneaky little things they were.
Got me thinking - generally speaking, unless there is a circumstance that specifically requires non-keyword arguments - is there any good reason NOT to use keyword arguments? Is it considered bad style to always use them, even for simple functions?
I feel like as most of my 50-line programs have been scaling to 500 or more lines regularly, if I just get accustomed to always using keyword arguments, the code will be more easily readable and maintainable as it grows. Any reason this might not be so?
UPDATE:
The general impression I am getting is that its a style preference, with many good arguments that they should generally not be used for very simple arguments, but are otherwise consistent with good style. Before accepting I just want to clarify though - is there any specific non-style problems that arise from this method - for instance, significant performance hits?
There isn't any reason not to use keyword arguments apart from the clarity and readability of the code. The choice of whether to use keywords should be based on whether the keyword adds additional useful information when reading the code or not.
I follow the following general rule:
If it is hard to infer the function (name) of the argument from the function name – pass it by keyword (e.g. I wouldn't want to have text.splitlines(True) in my code).
If it is hard to infer the order of the arguments, for example if you have too many arguments, or when you have independent optional arguments – pass it by keyword (e.g. funkyplot(x, y, None, None, None, None, None, None, 'red') doesn't look particularly nice).
Never pass the first few arguments by keyword if the purpose of the argument is obvious. You see, sin(2*pi) is better than sin(value=2*pi), the same is true for plot(x, y, z).
In most cases, stable mandatory arguments would be positional, and optional arguments would be keyword.
There's also a possible difference in performance, because in every implementation the keyword arguments would be slightly slower, but considering this would be generally a premature optimisation and the results from it wouldn't be significant, I don't think it's crucial for the decision.
UPDATE: Non-stylistical concerns
Keyword arguments can do everything that positional arguments can, and if you're defining a new API there are no technical disadvantages apart from possible performance issues. However, you might have little issues if you're combining your code with existing elements.
Consider the following:
If you make your function take keyword arguments, that becomes part of your interface.
You can't replace your function with another that has a similar signature but a different keyword for the same argument.
You might want to use a decorator or another utility on your function that assumes that your function takes a positional argument. Unbound methods are an example of such utility because they always pass the first argument as positional after reading it as positional, so cls.method(self=cls_instance) doesn't work even if there is an argument self in the definition.
None of these would be a real issue if you design your API well and document the use of keyword arguments, especially if you're not designing something that should be interchangeable with something that already exists.
If your consideration is to improve readability of function calls, why not simply declare functions as normal, e.g.
def test(x, y):
print "x:", x
print "y:", y
And simply call functions by declaring the names explicitly, like so:
test(y=4, x=1)
Which obviously gives you the output:
x: 1
y: 4
or this exercise would be pointless.
This avoids having arguments be optional and needing default values (unless you want them to be, in which case just go ahead with the keyword arguments! :) and gives you all the versatility and improved readability of named arguments that are not limited by order.
Well, there are a few reasons why I would not do that.
If all your arguments are keyword arguments, it increases noise in the code and it might remove clarity about which arguments are required and which ones are optionnal.
Also, if I have to use your code, I might want to kill you !! (Just kidding), but having to type the name of all the parameters everytime... not so fun.
Just to offer a different argument, I think there are some cases in which named parameters might improve readability. For example, imagine a function that creates a user in your system:
create_user("George", "Martin", "g.m#example.com", "payments#example.com", "1", "Radius Circle")
From that definition, it is not at all clear what these values might mean, even though they are all required, however with named parameters it is always obvious:
create_user(
first_name="George",
last_name="Martin",
contact_email="g.m#example.com",
billing_email="payments#example.com",
street_number="1",
street_name="Radius Circle")
I remember reading a very good explanation of "options" in UNIX programs: "Options are meant to be optional, a program should be able to run without any options at all".
The same principle could be applied to keyword arguments in Python.
These kind of arguments should allow a user to "customize" the function call, but a function should be able to be called without any implicit keyword-value argument pairs at all.
Sometimes, things should be simple because they are simple.
If you always enforce you to use keyword arguments on every function call, soon your code will be unreadable.
When Python's built-in compile() and __import__() functions gain keyword argument support, the same argument was made in favor of clarity. There appears to be no significant performance hit, if any.
Now, if you make your functions only accept keyword arguments (as opposed to passing the positional parameters using keywords when calling them, which is allowed), then yes, it'd be annoying.
I don't see the purpose of using keyword arguments when the meaning of the arguments is obvious
Keyword args are good when you have long parameter lists with no well defined order (that you can't easily come up with a clear scheme to remember); however there are many situations where using them is overkill or makes the program less clear.
First, sometimes is much easier to remember the order of keywords than the names of keyword arguments, and specifying the names of arguments could make it less clear. Take randint from scipy.random with the following docstring:
randint(low, high=None, size=None)
Return random integers x such that low <= x < high.
If high is None, then 0 <= x < low.
When wanting to generate a random int from [0,10) its clearer to write randint(10) than randint(low=10) in my view. If you need to generate an array with 100 numbers in [0,10) you can probably remember the argument order and write randint(0, 10, 100). However, you may not remember the variable names (e.g., is the first parameter low, lower, start, min, minimum) and once you have to look up the parameter names, you might as well not use them (as you just looked up the proper order).
Also consider variadic functions (ones with variable number of parameters that are anonymous themselves). E.g., you may want to write something like:
def square_sum(*params):
sq_sum = 0
for p in params:
sq_sum += p*p
return sq_sum
that can be applied a bunch of bare parameters (square_sum(1,2,3,4,5) # gives 55 ). Sure you could have written the function to take an named keyword iterable def square_sum(params): and called it like square_sum([1,2,3,4,5]) but that may be less intuitive, especially when there's no potential confusion about the argument name or its contents.
A mistake I often do is that I forget that positional arguments have to be specified before any keyword arguments, when calling a function. If testing is a function, then:
testing(arg = 20, 56)
gives a SyntaxError message; something like:
SyntaxError: non-keyword arg after keyword arg
It is easy to fix of course, it's just annoying. So in the case of few - lines programs as the ones you mention, I would probably just go with positional arguments after giving nice, descriptive names to the parameters of the function. I don't know if what I mention is that big of a problem though.
One downside I could see is that you'd have to think of a sensible default value for everything, and in many cases there might not be any sensible default value (including None). Then you would feel obliged to write a whole lot of error handling code for the cases where a kwarg that logically should be a positional arg was left unspecified.
Imagine writing stuff like this every time..
def logarithm(x=None):
if x is None:
raise TypeError("You can't do log(None), sorry!")

dumping the source code for an anonymous function

original (update follows)
I'm working with a lot of anonymous functions, ie functions declared as part of a dictionary, aka "methods". It's getting pretty painful to debug, because I can't tell what function the errors are happening in.
Vim's backtraces look like this:
Error detected while processing function NamedFunction..2111..2105:
line 1:
E730: using List as a String
This trace shows that the error occurred in the third level down the stack, on the first line of anonymous function #2105. IE NamedFunction called anonymous function #2111, which called anonymous function #2105. NamedFunction is one declared through the normal function NamedFunction() ... endfunction syntax; the others were declared using code like function dict.func() ... endfunction.
So obviously I'd like to find out which function has number 2105.
Assuming that it's still in scope, it's possible to find out what Dictionary entry references it by dumping all of the dictionary variables that might contain that reference. This is sort of awkward and it's difficult to be systematic about it, though I guess I could code up a function to search through all of the loaded dictionaries for a reference to that function, watching out for circular references. Although to be really thorough, it would have to search not only script-local and global dictionaries, but buffer-local dictionaries as well; is there a way to access another buffer's local variables?
Anyway I'm wondering if it's possible to dump the source code for the anonymous function instead. This would be a lot easier and probably more reliable.
update
I ended up asking about this a while back on the vim_use mailing list. Bram Moolenar, aka vim's BDFL, responded by saying that "You are not supposed to use the function number." However, a suitable alternative for this functionality has not been suggested, as of early September 2010. It's also not been explicitly mentioned whether or not this functionality will continue to work in subsequent vim releases. I've not tried to do this (or anything else, for that matter) in the recently released vim 7.3.
The :function command tries to stop you from specifying the numbered functions (their name is just a number) but you can trick it using the {...} dynamic function name feature, throw in some :verbose and you have a winner:
:verbose function {43}
function 43()
Last set from /home/peter/test.vim
1 throw "I am an exception"
endfunction
This was not at all obvious in the help docs.
I use the following workaround: I have one plugin that does some stuff like creating commands, global functions for other plugins. It also registers all plugins, so I have a large dictionary with lots of stuff related to plugins. If I see a error I search for a function that produces it using function findnr:
"{{{3 stuf.findf:
function s:F.stuf.findf(nr, pos, d)
if type(a:d)==2 && string(a:d)=~#"'".a:nr."'"
return a:pos
elseif type(a:d)==type({})
for [key, Value] in items(a:d)
let pos=s:F.stuf.findf(a:nr, a:pos."/".key, Value)
unlet Value
if type(pos)==type("")
return pos
endif
endfor
endif
return 0
endfunction
"{{{3 stuf.findr:
function s:F.stuf.findnr(nr)
for [key, value] in items(s:g.reg.registered)+[["load", {"F": s:F}]]
let pos=s:F.stuf.findf(a:nr, "/".key, value.F)
if type(pos)==type("")
return pos
endif
endfor
return 0
endfunction
Here I have this plugin functions in s:F.{key} dictionaries and other plugins' functions under s:g.reg.registered[plugname].F dictionary.

Resources