开发者

Can discriminated unions refer to each other?

开发者 https://www.devze.com 2023-01-08 15:13 出处:网络
I\'m building an expression tree using discriminated uni开发者_如何学编程ons. The below code:

I'm building an expression tree using discriminated uni开发者_如何学编程ons. The below code:

type IntExpression =
    | TrueIsOne of BoolExpression

type BoolExpression =
    | LessThan of IntExpression * IntExpression
    | And of BoolExpression * BoolExpression
    | Or of BoolExpression * BoolExpression
    | Bool of bool

throws an error because BoolExpression is not defined. Swapping the definitions just results in the reverse (IntExpression is not defined) as you would expect.

Is there a way around this?


Yes, use and to group type definitions with inter-dependencies:

type IntExpression =
    | TrueIsOne of BoolExpression

and BoolExpression =
    | LessThan of IntExpression * IntExpression
    | And of BoolExpression * BoolExpression
    | Or of BoolExpression * BoolExpression
    | Bool of bool


"and" works generally for types with mutual dependencies. That is, it works for all types, such as discriminated unions, as shown by Mau, classes, records and mutually recursive functions.

Non terminating example:

let rec foo x = bar x
and bar x = foo x


Perhaps this will work:

type IntExpression =
  ...
and BoolExpression = 
  ...

(Information taken from this page on MSDN.)

0

精彩评论

暂无评论...
验证码 换一张
取 消