I also wanted to do what you're doing when I started with Julia. I came 
from Java, so I'm used to the foo.func() syntax.
Here is a good way to do what I think you want with very similar syntax.

immutable Foo
end
func(::Foo, x) = x^2
foo = Foo()
func(foo, 3.)

You can also encapsulate parameters within instances of Foo like this. 
(reload Julia or use workspace() before redefining the type Foo)

immutable Foo
  a::Float64
end
func(foo::Foo, x) = foo.a * x^2
foo = Foo(5.)
func(foo, 3.)


Also, if you want to call the foo object directly, you can do this.

Base.call(foo::Foo, x) = func(foo, x)
foo(3.)

This is useful if you want to treat foo like a function and pass it to an 
optimization routine for example and don't want to use anonymous functions. 
It sometimes doesn't work correctly because foo won't be of type ::Function 
so some methods won't accept it, even though it acts like a function. I 
believe they are working on changing this.




On Monday, January 18, 2016 at 10:08:38 AM UTC-5, Anonymous wrote:
>
> Is the following code considered bad form in Julia?
>
> immutable Foo
> func::Function
> end
>
> foo = Foo(x->x^2)
> foo.func(3)
>
> This mimics the behavior of OOP since just like in OOP the internal method 
> cannot be changed (since the type is immutable).  Sometimes it really does 
> make the most sense to attach a function to an instance of a type, do I 
> take a performance hit doing things this way?
>

Reply via email to