Is it possible to declare a type at function scope in F#?
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:
开发者_如何学Clet 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?
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).
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.)
What Brian said.
heres a link to some more information http://www.ctocorner.com/fsharp/book/ch17.aspx
精彩评论