Tuesday 8 March 2016

Julia: Return function from other function


In Julia, you can return a function from other function.
julia> function addXtoY(x)
           return function add(y)
               x+y
           end
       end
addXtoY (generic function with 1 method)

julia> f = addXtoY(10)
add (generic function with 1 method)

julia> f(20)
30

julia> f(15)
25

julia> f(-10)
0

Function ‘addXtoY’ return other function which add the variable x to y.

addXtoY(x) =  f(x+y) = x+y

addXtoY(10) = f(10+y) = x+y

f(20) = 10+20 = 20
f(15) = 15 + 10 = 25
f(-10) = -10 + 10 = 0

Return anonymous function from other function
Just like returning a function from other function, you can return anonymous function from other function.

julia> function arithmetic(a, b)
           () -> a+b, () -> a-b, () -> a*b, () -> a/b
        end
arithmetic (generic function with 1 method)

julia> (sum, sub, mul, div) = arithmetic(10, 20)
((anonymous function),(anonymous function),(anonymous function),(anonymous function))

julia> sum()
30

julia> sub()
-10

julia> mul()
200

julia> div()
0.5




Previous                                                 Next                                                 Home

No comments:

Post a Comment