F# Subtype Discriminated Unions -


i have du this:

type food = | beer | bacon | apple | cherry 

i want add characteristic du flag if food fruit or not. first thought of this:

type nonfruit = nonfruit type fruit = fruit  type food = | beer of nonfruit | bacon of nonfruit | apple of fruit | cherry of fruit 

and method this:

let fruitchecker (myfood:food) = match myfood | :? nonfruit -> "no" | :? fruit -> "yes"

but compiler yelling @ me:

the type 'food' not have proper subtypes , cannot used source

am approaching problem incorrectly?

thanks

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


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -