Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of => in julia

Tags:

julia

From my understanding => used to bound string as a variable name.

For ex,

df1 = DataFrame(x=1:2, y= 11: 12)

df2 = DataFrame("x"=>1:2, "y"=> 11: 12)

Both returns same result,

│ Row │ x     │ y     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 11    │
│ 2   │ 2     │ 12    │

Here the only difference is in df1's x variable holds 1:2 whereas in df2's "x" string holds 1:2. So, from the above result, I presumed to create variable from string I can use =>.

But when I tried holding values in simple variable like below

x = 10

O/P: 10

"y"=>10

O/P: "y" => 10

This result I couldn't understand. When I print x it has 10 as expected. But when I print y I am getting UndefVarError. I found the same effect with Symbol also :z =>10

My assumption about => is wrong I guess. Because string is actually not converted as a new variable.

What is the actual purpose of => in julia? In which I have to use => rather than =?

like image 384
Mohamed Thasin ah Avatar asked Jul 06 '20 15:07

Mohamed Thasin ah


1 Answers

To understand what => means just write:

@edit 1 => 2

and in the source you will see:

Pair(a, b) = Pair{typeof(a), typeof(b)}(a, b)
const => = Pair

So a => b is just a shorthand for Pair(a, b). Therefore it just creates an object of type Pair holding a and b. It is a call (in this case a call to the constructor). That is all to it. It has no special meaning in the language. Just as 1 ÷ 2 is just the same as div(1, 2).

Notably, you will find => used in Dict and in DataFrames.jl as in a => b form a and b can be anything. Just to give a comparison:

df1 = DataFrame(x=1:2, y=11:12)

calls DataFrame constructor with two keyword arguments x and y. The issue is that keyword arguments are restricted to be valid identifiers (e.g. they do not allow spaces), so not all data frames that you could envision can be created using this constructor.

Now

df2 = DataFrame("x"=>1:2, "y"=>11:12)

calls DataFrame constructor with two positional arguments that are "x"=>1:2 and "y"=>11:12. Now, as Pair can hold anything on the left hand side, you can e.g. pass a string as a column name (and a string can contain any sequence of characters you like).

In other words DataFrame(x=1:2, y=11:12) and DataFrame("x"=>1:2, "y"=>11:12) are calls to two separate constructors of a data frame (they have completely different implementation in DataFrames.jl package). Actually I would even remove DataFrame(x=1:2, y=11:12) as obsolete (it is less flexible than the latter form), but it is provided for legacy reasons (and in toy examples it is a bit easier to type).

like image 163
Bogumił Kamiński Avatar answered Sep 26 '22 17:09

Bogumił Kamiński