Let's say I have a function which does something pretty complicated and it is implemented with the help of subfunctions. To make things easier, instead of tuples I would like to use some intermediate structures which are private to the implementation of this function.
I don't want the declaration of these structures to leak outside. So I want something like this:
let someComplexFun p =
type SomeRecord = {i:int; x:int; y:int;}
type SomeOtherRecord = {...}
let innerFunctionA (x:SomeRecord) = ...
let innerFunctionB (x:SomeOtherRecord) = ...
...
I tried it but of course the compiler doesn't let me do this. I looked at the documentation and I can't see anywhere quickly that the types must be declared at the module level.
In LISP for example, it seems that it's all entirely legal, e.g.:
(defun foo (when)
(declare (type (member :now :later) when)) ; Type declaration is illustrative and in this case optional.
(ecase when
(:now (something))
(:later (something-else))))
So, am I missing something? Is this possible if F# at all?
Types can only be declared at module or namespace scope in F#.
(You can use access modifiers like internal
or signature files to hide types from other components.)
To verify that this is not allowed according to the specification, take a look at the grammar of F# expressions in the specification: Section 6: Expressions. It lists various constructs that can be used in place of expr
and none of them is a type declaration type-defn
(described in Section 8: Type Declarations).
The (simplified) syntax for function declarations is let ident args = expr
, so the body has to be an expression (and you cannot declare types inside expressions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With