Li Haoyi
Li Haoyi

Reputation: 15802

Overloading function-call-behaviour in F#?

Can it be done? I've been digging around and haven't found anything as to whether or not it is possible.

The main reason I want to overload function call behavior is I have ended up with some code which uses some really complex closures, which capture lots and lots of local state to work with.

I find this sort of nested closures really confusing, and would like to convert them to full-fledged objects with a well-defined schema and inheritance and such, without changing the interface to the rest of the code.

Upvotes: 1

Views: 129

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

F# does not support overloading of function application behavior, so you can't write object that can be invoked in the same way as function. I'm afraid that you'll have to change the interface to use something like:

foo.Invoke(10, "Hello")

Instead of:

foo 10 "Hello"

The use of objects generally also suggests that the entity is more complex, so by changing the interface, you give some hint to the developer calling it (saying that this is a complex type). Depending on your domain, you should also find some more descriptive name for Invoke.

I also changed the syntax to use tupled method parameters instead of curried style - technically, you can use curried style for members too, but it is not generally used (it just works better for simple functions).

Finally, if you're finding that the closures represent more complex data structure, maybe you could make the data structure more explicit and define a type to hold the data. Then you could just use plain functions, but give them the data as an additional argument (although this is just a thought that may not really be useful for you).

Upvotes: 4

Related Questions