Search code examples
juliaijulia-notebook

(x:y) operator in Julia


I am trying to understand this code:

  r = (1:10) - (4/1)
    println(r)

Output:

-3.0:1.0:6.0

I understood why I got -3 and 6. But why I got that value in the middle (1.0)? How does Julia calculate it? Or how I can google it?


Solution

  • (first:step:last) syntax represent a Range type in Julia

    typeof(1:10) # => UnitRange{Int32}
    

    If step part is omitted, by default it is assumed 1

    1:10 == 1:1:10 # => true
    

    A Range is a compact view of a series

    collect(1:10) # => 10-element Array{Int32,1}:
    #  1
    #  2
    #  3
    #  4
    #  5
    #  6
    #  7
    #  8
    #  9
    # 10
    

    So it's expected that a Range type and a Vector follow the same rules e.g when you add a constant value like this:

    collect(1+(1:10))==collect(1:10)+1 # => true
    

    or even adding two vectors give you the same result of adding their range representation like this:

    collect((1:10)+(1:10))==collect(1:10)+collect(1:10) # => true