What does this syntax mean (...) [duplicate] - syntax

This question already has answers here:
What are these three dots in React doing?
(23 answers)
Closed 4 years ago.
I'm putting my hands into reason-react.
In the following code :
let component = ReasonReact.statelessComponent("Component3");
let make = (~name, _children) => {
...component,
render: self => <input type_="checkbox" />,
};
I don't understand what (...) means on line 3.
When I delete it I get an error message :
The record field component can't be found.
If it's defined in another module or file, bring it into scope by:
- Annotating it with said module name: let baby = {MyModule.age: 3}
- Or specifying its type: let baby: MyModule.person = {age: 3}

The representation is called Spread Syntax. This was introduced in ES6.
Definition and example from MDN Docs. Link at the bottom.
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
More details at : Spread Syntax

Related

Kotlin: Sort list by mutliple attributes [duplicate]

This question already has answers here:
How to sort based on/compare multiple values in Kotlin?
(3 answers)
Closed 2 years ago.
Let's say I have the following code:
val list = mutableListOf("abab", "abcd", "aaa")
list.sortBy { it.length } //result: [aaa, abab, abcd]
This sorts the list by the lengths of the Strings.
How do I break draws (2 Strings of the same length) by some other rule, lets say number of appearance of the char 'a'.
This way, one would have a hirarchy of comparison-rules: First length, then break draws by number of 'a', then maybe some other rule.
The function sortBy only receives a selector, which maps the elements to a comparable value, which is not capable for what I want to do I think.
Use sortWith and a custom comparator
val list = mutableListOf("abab", "abcd", "aaa")
list.sortWith(compareBy(String::length).thenBy { it.count { char -> char == 'a'} })
Here you can see documentation for all functions that will help you create a new comparator:
kotlin.comparisons

Binding vs Assignment

I've read a number of articles on the difference between assignment and binding, but it hasn't clicked yet (specifically in the context of an imperative language vs one without mutation).
I asked in IRC, and someone mentioned these 2 examples illustrate the difference, but then I had to go and I didn't see the full explanation.
Can someone please explain how/why this works in a detailed way, to help illustrate the difference?
Ruby
x = 1; f = lambda { x }; x = 2; f.call
#=> 2
Elixir
x = 1; f = fn -> x end; x = 2; f.()
#=> 1
I've heard this explanation before and it seems pretty good:
You can think of binding as a label on a suitcase, and assignment as a
suitcase.
In other languages, where you have assignment, it is more like putting a value in a suitcase. You actually change value that is in the suitcase and put in a different value.
If you have a suitcase with a value in it, in Elixir, you put a label on it. You can change the label, but the value in the suitcase is still the same.
So, for example with:
iex(1)> x = 1
iex(2)> f = fn -> x end
iex(3)> x = 2
iex(4)> f.()
1
You have a suitcase with 1 in it and you label it x.
Then you say, "Here, Mr. Function, I want you to tell me what is in this suitcase when I call you."
Then, you take the label off of the suitcase with 1 in it and put it on another suitcase with 2 in it.
Then you say "Hey, Mr. Function, what is in that suitcase?"
He will say "1", because the suitcase hasn't changed. Although, you have taken your label off of it and put it on a different suitcase.
After a while, I came up with the answer that is probably the best explanation of the difference between “binding” and “assignment”; it has nothing in common with what I have written in another answer, hence it’s posted as a separate answer.
In any functional language, where everything is immutable, there is no meaningful difference between terms “binding” and “assignment.” One might call it either way; the common pattern is to use the word “binding,“ explicitly denoting that it’s a value bound to a variable. In Erlang, for instance, one can not rebound a variable. In Elixir this is possible (why, for God’s sake, José, what for?)
Consider the following example in Elixir:
iex> x = 1
iex> 1 = x
The above is perfectly valid Elixir code. It is evident, one cannot assign anything to one. It is neither assignment nor binding. It is matching. That is how = is treated in Elixir (and in Erlang): a = b fails if both are bound to different values; it returns RHO if they match; it binds LHO to RHO if LHO is not bound yet.
In Ruby it differs. There is a significant difference between assignment (copying the content,) and binding (making a reference.)
Elixir vs Ruby might not be the best contrast for this. In Elixir, we can readily "re-assign" the value of a previously assigned named variable. The two anonymous-function examples you provided demonstrate the difference in how the two languages assign local variables in them. In Ruby, the variable, meaning the memory reference, is assigned, which is why when we change it, the anonymous function returns the current value stored in that memory-reference. While in Elixir, the value of the variable at the time the anonymous function is defined (rather than the memory reference) is copied and stored as the local variable.
In Erlang, Elixir's "parent" language, however, variables as a rule are "bound." Once you've declared the value for the variable named X, you are not allowed to alter it for the remainder of the program and any needed alterations would need to be stored in new named variables. (There is a way to reassign a named variable in Erlang but it is not the custom.)
Binding refers to particular concept used in expression-based languages that may seem foreign if you're used to statement-based languages. I'll use an ML-style example to demonstrate:
let x = 3 in
let y = 5 in
x + y
val it : int = 8
The let... in syntax used here demonstrates that the binding let x = 3 is scoped only to the expression following the in. Likewise, the binding let y = 5 is only scoped to the expression x + y, such that, if we consider another example:
let x = 3 in
let f () =
x + 5
let x = 4 in
f()
val it : int = 8
The result is still 8, even though we have the binding let x = 4 above the call to f(). This is because f itself was bound in the scope of the binding let x = 3.
Assignment in statement-based languages is different, because the variables being assigned are not scoped to a particular expression, they are effectively 'global' for whatever block of code they're in, so reassigning the value of a variable changes the result of an evaluation that uses the same variable.
The easiest way to understand the difference, would be to compare the AST that is used by the language interpreter/compiler to produce machine-/byte-code.
Let’s start with ruby. Ruby does not provide the AST viewer out of the box, so I will use RubyParser gem for that:
> require 'ruby_parser'
> RubyParser.new.parse("x = 1; f = -> {x}; x = 2; f.()").inspect
#=> "s(:block, s(:lasgn, :x, s(:lit, 1)),
# s(:lasgn, :f, s(:iter, s(:call, nil, :lambda), 0, s(:lvar, :x))),
# s(:lasgn, :x, s(:lit, 2)), s(:call, s(:lvar, :f), :call))"
The thing we are looking for is the latest node in the second line: there is x variable inside the proc. In other words, ruby expects the bound variable there, named x. At the time the proc is evaluated, x has a value of 2. Hence the the proc returns 2.
Let’s now check Elixir.
iex|1 ▶ quote do
...|1 ▶ x = 1
...|1 ▶ f = fn -> x end
...|1 ▶ x = 2
...|1 ▶ f.()
...|1 ▶ end
#⇒ {:__block__, [],
# [
# {:=, [], [{:x, [], Elixir}, 1]},
# {:=, [], [{:f, [], Elixir}, {:fn, [], [{:->, [], [[], {:x, [], Elixir}]}]}]},
# {:=, [], [{:x, [], Elixir}, 2]},
# {{:., [], [{:f, [], Elixir}]}, [], []}
# ]}
Last node in the second line is ours. It still contains x, but during a compilation stage this x will be evaluated to it’s currently assigned value. That said, fn -> not_x end will result in compilation error, while in ruby there could be literally anything inside a proc body, since it’ll be evaluated when called.
In other words, Ruby uses a current caller’s context to evaluate proc, while Elixir uses a closure. It grabs the context it encountered the function definition and uses it to resolve all the local variables.

Binary operator '/' cannot be applied to two (Int) operands [duplicate]

This question already has answers here:
Passing lists from one function to another in Swift
(2 answers)
Closed 7 years ago.
I am getting a Binary operator '/' cannot be applied to two (Int) operands error when I put the following code in a Swift playground in Xcode.
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
The above was a function calculating the total sum of any numbers.
Below is a function calculating the average of the numbers. The function is calling the sumOf() function from within itself.
func avg(numbers: Int...) -> Float {
var avg:Float = ( sumOf(numbers) ) / ( numbers.count ) //Binary operator '/' cannot be applied to two (Int) operands
return avg
}
avg(1, 2, 3);
Note: I have looked everywhere in stack exchange for the answer, but the questions all are different from mine because mine is involving two Ints, the same type and not different two different types.
I would like it if someone could help me to solve the problem which I have.
Despite the error message it seems that you cannot forward the sequence (...) operator. A single call of sumOf(numbers) within the agv() function gives an error cannot invoke sumOf with an argument of type ((Int))
The error is telling you what to do. If you refer to https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_operators.html
/ Division.
A binary arithmetic operator that divides the number to its left by the number to its right.
Class of operands: integer, real
Class of result: real
The second argument has to be real. Convert it like so. I don't use xcode, but I think my syntax is correct.
var avg:Float = ( sumOf(numbers) ) / Float( numbers.count )

Compare enum variants without specifying what's inside [duplicate]

This question already has an answer here:
Compare enums only by variant, not value
(1 answer)
Closed 5 years ago.
I have an enum with some nested values. I want to check that this enum is of given variant but without specifying what's inside. Check the following program:
enum Test {
Zero,
One(u8),
Two(u16),
Four(u32),
}
fn check(x: Test, y: Test) -> bool {
x == y;
}
fn main() {
let x = Test::Two(10);
let b1 = check(x, Test::One);
let b2 = check(x, Test::Two);
let b3 = match x {
Test::Four(_) => true,
_ => false,
}
}
b3 checks that x is Test::Four with an arbitrary value inside. I want that check to be done in the function check. Current code does not compile and I can't figure out how can I extract only enum variant without corresponding inside values.
I guess that could done with macro transforming to match expression, but is it possible to do that without macro?
I can see that Test::One is fn(u16) -> Test {Two}. Can I use that fact? To test that x was created using that function.
This is not supported (yet). There is the active RFC 639 which suggests implementing a function that returns an integer which corresponds to the enum discriminant. With that hypothetical function you could expect the following to work:
assert_eq!(Test::Two(10).discriminant(), Test::Two(42).discriminant());

Change variable passed in a method [duplicate]

This question already has answers here:
'pass parameter by reference' in Ruby?
(6 answers)
Closed 8 years ago.
How can I change the contents of a variable using a method? Maybe I'm not saying this correctly. What is a way to get the reference to a variable like in C? Example:
// main stuff
int gorilla = 29;
makeMeABanana(&gorilla);
void makeMeABanana(int *gorilla) { }
How can I do something like this in Ruby?
You should not do this - you're just porting techniques that are fully appropriate to C to Ruby, where they are no longer appropriate. There are several fancy ways around this (eg using a Proc closed over your calling namespace, or eval) but they are usually inappropriate in Ruby unless you know precisely what you're doing.
Recently on the ruby-talk mailing list, someone asked about writing a swap function where swap(a,b) would swap the values of the variables "a" and "b". Normally this cannot be done in Ruby because the swap function would have no reference to the binding of the calling function.
However, if we explictly pass in the binding, then it is possible to write a swap-like function. Here is a simple attempt:
def swap(var_a, var_b, vars)
old_a = eval var_a, vars
old_b = eval var_b, vars
eval "#{var_a} = #{old_b}", vars
eval "#{var_b} = #{old_a}", vars
end
a = 22
b = 33
swap ("a", "b", binding)
p a # => 33
p b # => 22
This actually works! But it has one big drawback. The old values of "a" and "b" are interpolated into a string. As long as the old values are simple literals (e.g. integers or strings), then the last two eval statements will look like: eval "a = 33", vars". But if the old values are complex objects, then the eval would look like eval "a = #", vars. Oops, this will fail for any value that can not survive a round trip to a string and back.
Referred from : http://onestepback.org/index.cgi/Tech/Ruby/RubyBindings.rdoc
Integers are objects, with an id, like everything else in Ruby. They are implemented like this:
p (0..10).map{|n| n.object_id}
#=>[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
All other objects have even object_id numbers. There is no way to change 7 (object_id 15) into something else.

Resources