Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Subtype Discriminated Unions

Tags:

f#

I have a DU like this:

type Food =
| Beer
| Bacon
| Apple
| Cherry

I want to add a characteristic to the DU to flag if the food is a fruit or not. I first 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 is yelling at me:

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

Am I approaching the problem incorrectly?

Thanks

like image 516
Jamie Dixon Avatar asked Dec 14 '22 12:12

Jamie Dixon


1 Answers

Or, use Active Patterns: 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

like image 93
FoggyFinder Avatar answered Dec 28 '22 02:12

FoggyFinder