Content deleted Content added
Rescuing 6 sources and tagging 0 as dead. #IABot (v1.5.5) |
Julia example |
||
Line 369:
x = b(7); // x has value 49 (current = 42 in closure b)
x = a(7); // x has value 18 (current = 11 in closure a)
</source>
== In Julia ==
In [[Julia_(programming_language)|Julia]], methods are associated with types, so it is possible to make any arbitrary Julia object "callable" by adding methods to its type. (Such "callable" objects are sometimes called "functors.")
An example is this accumulator mutable struct (based on [[Paul Graham (computer programmer)|Paul Graham's]] study on programming language syntax and clarity):<ref>[http://www.paulgraham.com/accgen.html Accumulator Generator]</ref>
<source lang=Julia>
julia> mutable struct Accumulator
n::Int
end
julia> function (acc::Accumulator)(n2)
acc.n += n2
end
julia> a = Accumulator(4)
Accumulator(4)
julia> a(5)
9
julia> a(2)
11
julia> b = Accumulator(42)
Accumulator(42)
julia> b(7)
49
</source>
Such a accumulator can also be implemented using closure:
<source lang=Julia>
julia> function Accumulator(n0)
n = n0
function(n2)
n += n2
end
end
Accumulator (generic function with 1 method)
julia> a = Accumulator(4)
(::#1) (generic function with 1 method)
julia> a(5)
9
julia> a(2)
11
julia> b = Accumulator(42)
(::#1) (generic function with 1 method)
julia> b(7)
49
</source>
|