F # Subtype Discriminatory Unions

I have a DU like this:

type Food =
| Beer
| Bacon
| Apple
| Cherry

I want to add a characterization in DU to indicate whether food is a fruit or not. At first I thought of something like this:

type NonFruit = NonFruit
type Fruit = Fruit

type Food =
| Beer of NonFruit
| Bacon of NonFruit
| Apple of Fruit
| Cherry of Fruit

And then a method like this:

let fruitChecker (myFood: Food) = match myFood with | :? NonFruit → No | :? Fruit → Yes

But the compiler yells at me:

The type 'Food' does not have the proper subtypes and cannot be used as a source.

Am I getting the problem wrong?

thank

+4
source share
2 answers

Or use Active Templates: https://msdn.microsoft.com/en-us/library/dd233248.aspx

type Food =
| Beer
| Bacon
| Apple
| Cherry

let (|NonFruit|Fruit|) =
    function
    | Beer | Bacon -> NonFruit
    | Apple | Cherry -> Fruit

let fruitChecker = function | NonFruit -> "No" | Fruit -> "Yes"

[Beer;Bacon;Apple;Cherry] |> List.iter(fun x -> printfn "%s" (fruitChecker x))

Print

No
No
Yes
Yes

Link: https://dotnetfiddle.net/oRYDs6

+10
source

. "" , :

type Food =
   | Beer
   | Bacon
   | Apple
   | Cherry
   static member IsFruit = function Beer | Bacon -> false | Apple | Cherry -> true

DU - Beer, , .

+3

Source: https://habr.com/ru/post/1599870/


All Articles