Writing a mutable function (exclamation mark function)

457 views
Skip to first unread message

dwo...@gmail.com

unread,
Jun 8, 2015, 10:34:47 AM6/8/15
to julia...@googlegroups.com
I'm currently trying to understand how functions with an exclamation mark at the end work. I know the exclamation mark is just a notational point however I'm currently confused at how to actually write a mutable function.
If a = 1

function add_one(a)
    return a + 1
end

running add_one(a) twice outputs:
    2
    2

how would I create add_one!(a) to output:
    2
    3

John Myles White

unread,
Jun 8, 2015, 10:35:47 AM6/8/15
to julia...@googlegroups.com, dwo...@gmail.com

andrew cooke

unread,
Jun 8, 2015, 2:52:17 PM6/8/15
to julia...@googlegroups.com

does this help any?

julia> a = 1
1

julia
> function inc()
        a
= a+1
       
end
inc
(generic function with 1 method)

julia
> inc()
ERROR
: UndefVarError: a not defined
 
in inc at none:2

julia
> function inc()
       
global a = a+1
       
end
inc
(generic function with 1 method)

julia
> inc()
2

julia
> inc()
3

julia
> inc()
4

julia
> inc()
5

julia
> function make_inc(start)
        a
= start
       
function inc()
         a
= a + 1
       
end
       
end
make_inc
(generic function with 1 method)

julia
> inc2 = make_inc(99)
inc
(generic function with 1 method)

julia
> inc2()
100

julia
> inc2()
101

julia
> inc2()
102

also http://julia.readthedocs.org/en/latest/manual/variables-and-scoping/

andrew
Reply all
Reply to author
Forward
0 new messages