Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the raku equivalent of the JavaScript arrow function?

In JavaScript, I can go

const materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]

I guess that raku has some chops in functional - and I wonder if someone can clarify the equivalent code (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions )

like image 788
p6steve Avatar asked Jul 06 '20 20:07

p6steve


People also ask

What can I use instead of arrow in JavaScript?

Since arrow functions don't have their own arguments , you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments : the rest parameter. // old function sum() { let args = []. slice.

What is => called in JavaScript?

Arrow Functions Return Value by Default: hello = () => "Hello World!"; Try it Yourself »

What are the arrows in JavaScript?

Arrow functions introduce concise body syntax, or implicit return. This allows the omission of the curly brackets and the return keyword. Implicit return is useful for creating succinct one-line operations in map , filter , and other common array methods.

What are arrow functions in ES6 version of JavaScript?

Arrow functions are anonymous functions (the functions without a name and not bound with an identifier). They don't return any value and can declare without the function keyword. Arrow functions cannot be used as the constructors. The context within the arrow functions is lexically or statically defined.


1 Answers

The most direct equivalent would be

my @materials = <Hydrogen Helium Lithium Beryllium>;
say @materials.map(-> $material { $material.chars });

but an arrow sub is more explicit than you need in this case, because

say @materials.map: *.chars;

would also be sufficient (method call on a "whatever star" returns a code block that calls that method on its argument), and

say @materials».chars;

would also work (hyper-application applied to the dot operator).

like image 82
hobbs Avatar answered Nov 02 '22 18:11

hobbs