functional programming - F# - Can I return a discriminated union from a function -
i have following types:
type goodresource = { id:int; field1:string } type errorresource = { statuscode:int; description:string }
i have following discriminated union:
type processingresult = | of goodresource | error of errorresource
then want have function have return type of discriminated union processingresult:
let sampleprocessingfunction value = match value | "goodscenario" -> { id = 123; field1 = "field1data" } | _ -> { statuscode = 456; description = "desc" }
is trying possible. compiler giving out stating expects goodresource return type. missing or going wrong way?
as stands, sampleprocessingfunction
returns 2 different types each branch.
to return same type, need create du (which did) specify case of du explicitly, this:
let sampleprocessingfunction value = match value | "goodscenario" -> { id = 123; field1 = "field1data" } | _ -> error { statuscode = 456; description = "desc" }
you might ask "why can't compiler figure out correct case automatically", happens if du has 2 cases of same type? example:
type goodorerror = | of string | error of string
in example below, compiler cannot determine case mean:
let returngoodorerror value = match value | "goodscenario" -> "goodness" | _ -> "badness"
so again need use constructor case want:
let returngoodorerror value = match value | "goodscenario" -> "goodness" | _ -> error "badness"
Comments
Post a Comment