Monday, 29 February 2016

Julia: Create anonymous functions using do block

In previous post, I explained anonymous functions. You can create anonymous function using do statement also.

map((x) -> x^3, [1, 2, 3, 4, 5])

Above anonymous function is used to calculate x^3. Same anonymous function can be written like below.

map([1, 2, 3]) do x
    x^3
end
julia> map([1, 2, 3]) do x
           x^3
       end
3-element Array{Int64,1}:
  1
  8
 27

julia> map((x) -> x^3, [1, 2, 3, 4, 5])
5-element Array{Int64,1}:
   1
   8
  27
  64
 125

do x : Create an anonymous function with argument x.
do x, y : Create two argument anonymous function.


Previous                                                 Next                                                 Home

No comments:

Post a Comment