es6- arrow function- no duplicate named arguments - arguments

I can't understand well about the last ways of arrow functions have:
No duplicate named arguments- arrow functions cannot have duplicate
named arguments in strict or nonstrict mode, as opposed to nonarrow
functions that cannot have duplicate named arguments only in strict
mode.
The above paragraph was picked from Book "Understanding ECMAScript 6" wrote by Nicholas C. Zakas in 'Function' chapter.
According to description above, I know that arrow function has not arguments like other function.
I can understand well the sentence before half, but the other half start by "as opposed to...".
What's that mean "nonarrow functions that cannot have duplicate named arguments only in strict mode."
In fact, functions in strict mode also have arguments. I have no idea what the author mean.

It means that the following is valid JavaScript:
function bar(foo, foo){}
It is not, however, when using strict mode:
'use strict';
function bar(foo, foo){}
// SyntaxError: duplicate formal argument foo
With arrow functions, duplicate named arguments are always, regardless of strict or non-strict mode, invalid.
(foo, foo) => {}
// SyntaxError: duplicate argument names not allowed in this context
According to description above, I know that arrow function has not arguments like other function.
Not sure whether you understood this correctly. Arrow functions can have parameters, it just does not have arguments.

Related

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)

Using the name "function" for a variable in Python code

Is using the word function for the name of an argument considered bad style in Python code?
def conjunction_junction(function):
pass # do something and call function in here
This pattern occurs all the time, especially in decorators. You see func, fn and f used all of the time but I prefer to avoid abbreviations when possible. Is the fact that it's the name of a type enough to warrant abbreviating it?
>> type(conjunction_junction).__name__
'function'
It's not a reserved keyword, so I don't see why not.
From the Style Guide
If a function argument's name clashes with a reserved keyword, it is
generally better to append a single trailing underscore rather than
use an abbreviation or spelling corruption. Thus class_ is better than
clss. (Perhaps better is to avoid such clashes by using a synonym.)
Using function is perfectly fine.
There is nothing in the style guide about it specifically. The reason that the use of type names such as str and list is highly discouraged is because they have functionality within the language. Overwriting them would obscure the functionality of the code. function on the other hand, does nothing.
I suspect func, fn, and f are used because they are all shorter than typing function ;)

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!")

What is an "argument"?

Assuming I have this code:
function question($argument)
{
var $q = "What does ($argument) mean?";
}
Can any tell me is there any other word (or phrase) that defines what an argument is?
I'm asking this because English is my second language, and I can't for life find a word in my language that defines "argument" in "programming".
I understand how arguments work, and what they are for, I just need a synonym word or phrase to be able to translate it to my language to make it easy to use and understand.
The best thing that I came up with (in my language) is (Passed Variable(s)), does that sound right? Is there any better wording?
Thanks
Parameters
Does that help?
("Passed Variables" is close ... and might work fine in your language)
I wouldn't use "passed variable" because arguments do not have to be variables.
Perhaps the most common usage of the term is seen in this example. Consider
// A function definition
function f(x, y) {
....
}
// A function call
f(57/p*q+4, z);
Most people would call x and y parameters, and call 57/p*q+4 and z arguments. Note that parameters are variables (unless the language has pattern-matching, not too common) and that arguments can be arbitrary expressions.
Now you may hear people call x and y "formal parameters" while the arguments are "actual parameters" but IMHO this distinction is a little old-fashioned. I may be wrong though.
The thing is that the argument is the expression that is passed to the parameter in a function call. So maybe "passed expression" is better than "passed variable" at the very least. Have fun translating. One fun thing about the vocabulary of computing is that almost every word (function, procedure, type, label, constant, variable, expression, declaration, statement, operator, argument, parameter, etc.) is just borrowed from a plain old English word. There aren't too many novel terms.
On the calling side it's an argument, on the function side it's a parameter.
"Parameter" vs "Argument"
An argument is what you pass into a function (also known as a subroutine). Arguments are also known as parameters. A function might take an argument and use it to calculate something or modify the argument itself.
Arguments are the variables of the functions that works during calling them.
And
parameters are also the variables of the functions that works during returning value to the program by that function.

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