Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia 1.0.0: What does the `=>` operator do?

Tags:

julia

I see this Stackoverflow code for =>, but when I search Julia 1.0.0 on-line help for "=>", I get zero hits.

replace!(x, 0=>4)  # The last expression is the focus of this question.

In the REPL help I get:

help?> =>
search: =>

  Pair(x, y)
  x => y

Construct a Pair object with type Pair{typeof(x), typeof(y)}. The elements are stored in the fields first and second. They can also be accessed via iteration.

See also: Dict

Examples ≡≡≡≡≡≡≡≡≡≡

  julia> p = "foo" => 7
  "foo" => 7

  julia> typeof(p)
  Pair{String,Int64}

  julia> p.first
  "foo"

  julia> for x in p
             println(x)
         end
  foo
  7

What does => do in replace!(x, 0=>4)? Does it create a pair, a replacement of all zeros by fours, or what? Why do I seem to not find it in the Julia 1.0.0 on-line docs?

EDIT

Code added to help me understand @Bill's helpful answer below:

julia> x = [1, 0, 3, 2, 0]
5-element Array{Int64,1}:
 1
 0
 3
 2
 0

julia> replace!(x, 0=>4)
5-element Array{Int64,1}:
 1
 4
 3
 2
 4

Edit 2

Besides @Bill's accepted answer, I found @Steven's answer helpful as well. Sorry I could not check them both, but Bill's came in first and they both offered useful information.

like image 215
Julia Learner Avatar asked Sep 24 '18 23:09

Julia Learner


2 Answers

"What does => do in replace!(x, 0=>4)? Does it create a pair, a replacement of all zeros by fours, or what?"

It creates a Pair. In the function replace, a Pair in the second argument position means the multiple dispatch of replace() chooses a version of the replace function where, given a numeric array or string x, all items within x fitting the first part of the Pair are replaced with an instance of the second part of the Pair.

You can check the REPL docs for replace for details.

like image 101
Bill Avatar answered Nov 17 '22 22:11

Bill


This small example should show how "=>" makes a pair

julia> replace("julia", Pair("u", "o"))

"jolia"

julia> replace("julia", "u" => "o")

"jolia"
like image 45
Littlefairy Avatar answered Nov 17 '22 23:11

Littlefairy