Get a discriminatory association case ID according to a template

How can I get the inferred type after ->

according to the pattern?

For example:

type Type =
  | Complex1
  | Complex2
  | Number of int
  | Integer of int

let calculate = function
  | Number i -> Number (i + 1)
  | Integer i -> Integer (i + 1)
  | Complex1 | Complex2 as t -> t

      

I want to shorten this function by combining Number

and Integer

with a pattern or |

. How can I get the inferred case id to make the following work:

let calculate' = function
  | Number i | Integer i ->
      // If this is Number, return Number (i + 1)
      // Else return Integer (i + 1)
  | Complex1 | Complex2 as t -> t

      

+3


source to share


1 answer


If Integer

both are Number

semantically different, you don't want to combine them. After a few months it will be difficult to decipher and understand what you mean. The semantic difference should translate into a technical difference. This is a good thing.

Now, if they are in fact the same and are only presented in some cases for some meta-purposes, your data structure is wrong: this does not mean that these two cases are indeed the same case. To represent this fact correctly, fold them into one case and add a tag that identifies the type of number:

type NumberKind = Integer | Other

type Type =
  | Complex1
  | Complex2
  | Number of NumberKind * int

let calculate = function
  | Number (kind, i) -> Number (kind, i + 1)
  | Complex1 | Complex2 as t -> t

      



NOTE. If you find that you need to differentiate between the two, you can still match them:

let kind = function
  | Number (Integer, _) -> "integer"
  | Number (Other, _) -> "number"
  | Complex1 -> "complex 1"
  | Complex2 -> "complex 2"

      

+11


source







All Articles