I'm running this snippet in JS Bin:
let array1 = [1, 4, 9, 16]
let array2=[1, 4, 9, 16]
const map1=array2.map(x=>x*2)
console.log(map1)
//Output is:[2, 8, 18, 32]
const map2 = array2.map((y,x) => x * 2)
console.log(map2)
//Output is: [0, 2, 4, 6]
How is the first parameter affecting the output of map function?
Edit: Two precise answers. Just giving some context on why I asked this question. Thanks to SO, now I know that first parameter is value at the index, while second is the index of the array. I had seen this being used in an example: map((_,x)=>itemName+=x). If I pass only one parameter, it'd turn it into itemName+valueAtTheIndex, however if I pass two arguments and use the second, it will turn into itemName1,itemName2,.....
Quite handy!
_ is not affecting the output of .map. It's the argument you are using to do the calculation that's affecting the output.
.map(entry, index) is the syntax when you use two args in a map function.
let arr = [1, 4, 9, 16]
const ret = arr.map(x => x * 2)
console.log(ret)
// Output is: [2, 8, 18, 32]
// here, x is array index - 0, 1, 2, 3
const ret = arr.map((_, x) => x * 2)
console.log(ret)
// Output is: [0, 2, 4, 6]
// try it with `_`
// You'll get the desired output
const ret = arr.map((_, x) => _ * 2)
console.log(ret)
// Output is: [2, 8, 18, 32]
In your two snippets you call "x" two different things. In the first one x is the first argument of the function array.map(), which will contain each value, while in the second snippet x is the second argument and it will contain each array index.
In the first case x will contain the array values (which is what you expected) while in the second case x will contain the values 0,1,2,3, which yield the result you got.
The identifier _ has no special meaning but it is a valid argument identifier. you could have called it y and would have gotten the same result.
first argument in map function is the current value in your array while second column is index.
_ is used for ignoring the first column.
Related
R = [cos(pi/3) sin(pi/3); -sin(pi/3) cos(pi/3)]
[i,j]=round([1 1] * R)
returns
i =
-0 1
error: element number 2 undefined in return list
While I want i=0 and j=1
Is there a way to work around that? Or just Octave being stupid?
Octave is not being stupid; it's just that you expect the syntax [a,b] = [c,d] to result in 'destructuring', but that's not how octave/matlab works. Instead, you are assigning a 'single' output (a matrix) to two variables. Since you are not generating multiple outputs, there is no output to assign to the second variable you specify (i.e. j) so this is ignored.
Long story short, if you're after a 'destructuring' effect, you can convert your matrix to a cell, and then perform cell expansion to generate two outputs:
[i,j] = num2cell( round( [1 1] * R ) ){:}
Or, obviously, you can collect the output into a single object, and then assign to i, and j separately via that object:
[IJ] = round( [1 1] * R ) )
i = IJ(1)
j = IJ(2)
but presumably that's what you're trying to avoid.
Explanation:
The reason [a,b] = bla bla doesn't work, is because syntactically speaking, the [a,b] here isn't a normal matrix; it represents a list of variables you expect to assign return values to. If you have a function or operation that returns multiple outputs, then each output will be assigned to each of those variables in turn.
However, if you only pass a single output, and you specified multiple return variables, Octave will assign that single output to the first return variable, and ignore the rest. And since a matrix is a single object, it assigns this to i, and ignores j.
Converting the whole thing to a cell allows you to then index it via {:}, which returns all cells as a comma separated list (this can be used to pass multiple arguments into functions, for instance). You can see this if you just index without capturing - this results in 'two' answers, printed one after another:
num2cell( round( [1 1] * R ) ){:}
% ans = 0
% ans = 1
Note that many functions in matlab/octave behave differently, based on whether you call them with 1 or 2 output arguments. In other words, think of the number of output arguments with which you call a function to be part of its signature! E.g., have a look at the ind2sub function:
[r] = ind2sub([3, 3], [2,8]) % returns 1D indices
% r = 2 8
[r, ~] = ind2sub([3, 3], [2,8]) % returns 2D indices
% r = 2 2
If destructuring worked the way you assumed on normal matrices, it would be impossible to know if one is attempting to call a function in "two-outputs" mode, or simply trying to call it in "one-output" mode and then destructure the output.
Im trying to convert this function into a lambda function but I am unsure of how to utilize the rotate in lambda. Any help is appreciated.Function is below.
list = [1, 2, 5, 9, 11, 43, 16, 2]
def rotate(l, n):
return l[-n:] + l[:-n]
rotate(list, 3)
well this is a bit tautalogicial, but you can invoke the function in the lambda with the same parameters, something like this:
lambda l, n: rotate(l, n)
and even give it a name:
my_rotate = lambda l, n: rotate(l, n)
But after all that, you're just wrapping rotate in an identical function, so you're better off using rotate on it's own. As a preference, lambdas should be used for extremely simple functions in the next few lines
I want to get some data out of my MySQL database using Koa and the mysql node package. I was looking at co-mysql, but the readme suggests to use thunkify directly. So I did the following:
const query = thunkify(connection.query.bind(connection));
Which seems to work, as I now can do:
app.use(function * main() {
const races = yield query(
"SELECT * FROM `races` where '2016-01-19' between start_date and end_date"
)(function(err, rows) {
// rows is the data I need
});
});
However, I cannot find a way to return/yield the row data from the thunk into my races variable. I log it, and it displays the correct data, but when I try to pass it back, it always returns undefined. I've tried a couple of ways from inside the callback, but I can't seem to figure it out:
return rows
yield rows (made the callback a generator function)
return yield rows
...
I'm often getting: TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "undefined"
races is an array because you are using thunkify for query. co returns an array for any thunks that call their callback with more than one value (ie. callback(null, 1, 2, 3) returns [1, 2, 3].
If you were to Promisify query instead, races will be assigned to the first returned value only, which appears to be inline with what you're looking for.
Here's a code example showing it in practice:
var co = require("co")
var promisify = require("bluebird").promisify
var thunkify = require("thunkify")
function async(callback) {
callback(null, 1, 2, 3)
}
var p = promisify(async)
var t = thunkify(async)
co(function*() {
let x = yield p()
let y = yield t()
console.log(x)
console.log(y)
}).then(() => {})
When run, the value of x will be 1 and the value of y will be the array [1, 2, 3].
You can run it with Tonic here: https://tonicdev.com/56ab7cfc879afb0c002c1d49/56ab7cfc879afb0c002c1d4a
The use of the command "return" has always been bothering me since I started learning Python about a month ago(completely no programming background)
The function "double()" seems working fine without me have to reassign the value of the list used as an argument for the function and the value of the elements processed by the function would double as planned. Without the need to assign it outside the function.
However, the function "only_upper()" would require me to assign the list passed as argument through the function in order to see the effect of the function. I have to specify t=only_upper(t) outside of the function to see the effect.
So my question is this: Why are these two seemingly same function produces different result from the use of return?
Please explain in terms as plain as possible due to my inadequate programming skill. Thank you for your input.
def double(x):
for i in range(len(x)):
x[i] = int(x[i])*2
return x
x = [1, 2, 3]
print double(x)
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
t = res
return t
t = ['a', 'B', 'C']
t = only_upper(t)
print t
i am assuming that this is your first programming language hence the problem with understanding the return statement found in the functions.
The return in our functions is a means for us to literally return the values we want from that given 'formula' AKA function. For example,
def calculate(x,y):
multiply = x * y
return multiply
print calculate(5,5)
the function calculate defines the steps to be executed in a chunk. Then you ask yourself what values do you want to get from that chunk of steps. In my example, my function is to calculate the multiplied value from 2 values, hence returning the multiplied value. This can be shorten to the following
def calculate(x,y):
return x * y
print calculate(5,5)
I have been messing around with Haskell for two weeks now and have some functions written in Haskell. I heard that Erlang was quite similar(since they are both predominately functional) so I thought I would translate some of these functions to see if I could get them working in Erlang. However I have been having trouble with the syntax for this function I wrote. The purpose of this function is to simply take a character or int and go through a list. After it goes through the list I am just trying to count the amount of times that item occurs. Here is an example run it should return the following.
count (3, [3, 3, 2, 3, 2, 5]) ----> 3
count (c, [ a, b, c, d]) ----> 1
Whenever I run my code it just keeps spitting out syntax issues and it is really a pain debugging in Erlang. Here is the code I have written:
count(X,L) ->
X (L:ls) ->
X == L = 1+(count X ls);
count X ls.
Any ideas I can do to fix this?
It's not clear what you're going for, as your syntax is pretty far off. However, you could accomplish your call with something like this:
count(Needle, Haystack) -> count(Needle, Haystack, 0).
count(_, [], Count) -> Count;
count(X, [X|Rest], Count) -> count(X, Rest, Count+1);
count(X, [_|Rest], Count) -> count(X, Rest, Count).
To elaborate, you're creating a recursive function called count to find instances of Needle in Haystack. With each call, there are 3 cases to consider: the base case, where you have searched the entire list; the case in which the value you're searching for matches the first item in the list; and the case in which the value you're searching for does not match the first item in the list. Each case is a separate function definition:
count(_, [], Count) -> Count;
Matches the case in which the Haystack (i.e., the list you are scanning) is empty. This means you do not have to search anymore, and can return the number of times you found the value you're searching for in the list.
count(X, [X|Rest], Count) -> count(X, Rest, Count+1);
Matches the case in which the value you're searching for, X, matches the first item in the list. You want to keep searching the list for more matches, but you increment the counter before calling count again.
count(X, [_|Rest], Count) -> count(X, Rest, Count).
Matches the case in which the value you're searching for does not match the head of the list. In this case, you keep scanning the rest of the list, but you don't increment the counter.
Finally,
count(Needle, Haystack) -> count(Needle, Haystack, 0).
Is a helper that calls the three-argument version of the function with an initial count of 0.
Use list comprehension in Erlang:
Elem = 3,
L = [3, 3, 2, 3, 2, 5],
length([X || X <- L, X =:= Elem]) %% returns 3