F# forward type declarations
Asked Answered
P

3

35

I stumbled across this problem in F#. Suppose, I want to declare two types that reference each other:


type firstType = 
     | T1 of secondType
     //................

type secondType =
     | T1 of firstType  
     //................    

How do I do that, so the compiler does not generate an error?

Persas answered 4/9, 2009 at 11:5 Comment(1)
See also #681106Stanfill
N
55

You use 'and':

type firstType = 
     | T1 of secondType

and secondType =
     | T1 of firstType
Numerary answered 4/9, 2009 at 11:23 Comment(1)
Every time I feel something isn't elegant in F# I'm pleasantly surprised there's an elegant solution.Nochur
P
4

I figured it. It's:


type firstType = 
     | T1 of secondType
     //................

and secondType =
     | T1 of firstType  
     //................   
Persas answered 4/9, 2009 at 11:28 Comment(1)
you use the same notation for mutually recursive functions as well - in case you didn't already know that.Promethium
F
3

The limitation is that the types have to be declared in the same file.

Flightless answered 4/9, 2009 at 20:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.