Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 992
Philip P. Avatar asked Aug 25 '11 12:08

Philip P.


2 Answers

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.)

like image 40
Brian Avatar answered Nov 08 '22 22:11

Brian


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).

like image 141
Tomas Petricek Avatar answered Nov 09 '22 00:11

Tomas Petricek