Reputation: 9
I've seen there is a method one could use in a Scala type called apply. This would enable to call on a instance of the type as if it were a function or alike. Like for example the Scala list, one could write myList(0) for the first element in the list.
Is there anything like this in F#?
Upvotes: 1
Views: 166
Reputation: 29100
F# function application is based around the FSharpFunc
type internally. For example, (int -> int)
is represented as FSharpFunc<int, int>
.
However the F# compiler seems to somehow know the difference between a real F# function and a manual attempt to implement one, at least when the implementation language is F#.
However, I was able to fake an F# function by defining it in C#:
public class Foo : FSharpFunc<int, int>
{
public override int Invoke(int n)
{
return n + 1;
}
}
and then from F#:
> let x = Foo() :> int -> int
val x : (int -> int)
> x 3;;
val it : int = 4
I couldn't work the same trick when defining Foo
in F#, even when I define it in a separate compilation unit.
The F# compiler seems to insert an attribute CompilationMapping(SourceConstructFlags.ObjectType)
onto its own objects and I can't find a way to turn it off, but my C# works even if I put that attribute on manually.
Upvotes: 4