In pseudocode, the meaning of a method definition `f(a,b) = a + 2b` is something like this:
isdefined(:f) || const f = make_generic() add_method!(f, (a,b) -> a + 2b) On Fri, Apr 17, 2015 at 2:08 PM, Stefan Karpinski <[email protected]> wrote: > Since Julia functions are generic by default, adding methods cannot do > assignment of a function object to a binding, since otherwise only the last > definition given for any function would ever be part of the function. So > when you write this, for example: > > f(a,b) = a + 2b > f(a,b,c) = a + 2b + 3c > > > the meaning of the second line cannot be `f = (a,b,c) -> a + 2b + 3c` > since if that were the case, then the method defined by the first line > would be blown away. > > Another difference is that when you define a method of a generic function, > the binding to that function is const. You can have other non-const > bindings to the function, but the binding that is automatically created is > const. This is for performance: if you know what function a name refers to > you can do inlining and type inference; if you don't then you can't do > either of those things and you're basically screwed performance-wise. > > On Fri, Apr 17, 2015 at 1:26 PM, Ravi Mohan <[email protected]> wrote: > >> Hi, >> I'm learning Julia by working through the manual and came across >> something that tripped me a bit. >> I am sure this is just my not understanding things correctly >> >> ravi@ubuntu:~/projects/learnjulia$ julia -v >> julia version 0.3.6 >> >> >> julia> f = (x,y) -> x + y >> (anonymous function) >> >> julia> f(2,3) >> 5 >> >> julia> g = (x,y) -> x - y >> (anonymous function) >> >> julia> g (2,3) >> -1 >> >> julia> f = g >> (anonymous function) >> >> julia> f(2,3) >> -1 >> >> but this doesn't >> >> julia> function m(x,y) x + y end >> m (generic function with 1 method) >> >> julia> function n(x,y) x - y end >> n (generic function with 1 method) >> >> julia> m(2,3) >> 5 >> >> julia> n(2,3) >> -1 >> >> julia> m = n >> ERROR: invalid redefinition of constant m >> >> My "scripting" languages are Python and Scheme, where this works >> Python: >> >> >>> def f (x,y): >> ... return x + y >> ... >> >>> def g (x,y): >> ... return x - y >> ... >> >>> f(2,3) >> 5 >> >>> g(2,3) >> -1 >> >>> f = g >> >>> f(2,3) >> -1 >> >> and in Dr. Racket >> >> > (define (f x y) (+ x y)) >> > (f 2 3) >> 5 >> > (define (g x y) (- x y)) >> > (g 2 3 ) >> -1 >> > (set! f g) >> > (f 2 3) >> -1 >> >> So I'm guessing 'simple' and anonymous functions have different semantics >> wrt function names. the function m(x,y) ... end form seems to create a >> 'generic function' consider the name (here, m) to be a constant . I found >> this interesting. Could you help me understand ? As I said, while I am an >> experienced developer, I am new to Julia. >> (I'm guessing this has something to do with how multimethods work etc, >> and while I've read about CLOS etc,I've never used it in anger) >> >> Thanks in advance >> > >
