Sunday 28 February 2016

Julia: Using operators as functions


In Julia, most of the operators can be used as functions. Observe following Julia snippet.
help?> +
search: + .+

  +(x, y...)

  Addition operator. x+y+z+... calls this function with all arguments, i.e. +(x, y, z, ...).

help?> -
search: - .-

  -(x, y)

  Subtraction operator.

  -(x)

  Unary minus operator.

help?> *
search: * .*

  *(x, y...)

  Multiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).

  *(s, t)

  Concatenate strings. The * operator is an alias to this function.

  julia> "Hello " * "world"
  "Hello world"

  *(A, B)

  Matrix multiplication

help?> /
search: / // ./ .//

  /(x, y)

  Right division operator: multiplication of x by the inverse of y on the right. Gives floating-point results for integer arguments.


You can use almost all operators other than (&&, ||) as functions in Julia.
julia> +(20,30,40)
90

julia> -(20,30)
-10

julia> *(10,20,30)
6000

julia> /(30,10)
3.0

julia> \(30,10)
0.3333333333333333

julia> <<(2, 4)
32

julia> >>(32, 4)
2


Since operators in Julia are functions, you can assign them to some variables and use them.
julia> sum=+
+ (generic function with 171 methods)

julia> sub=-
- (generic function with 204 methods)

julia> mul=*
* (generic function with 138 methods)

julia> div=/
/ (generic function with 48 methods)

julia> sum(10, 20, 30)
60

julia> sub(10, 20)
-10

julia> mul(10, 20)
200

julia> div(10, 20)
0.5






Previous                                                 Next                                                 Home

No comments:

Post a Comment