Question

How do you go about deciding which of the following two representations (in F# syntax) is the right choice in a particular situation?

type Choice = A of string | B of string

Or:

type ChoiceKind = A | B
type Choice = { Kind: ChoiceKind; Value: string }

I'm deliberately avoiding giving a more specific example, as either approach can "feel more natural" in a particular scenario; I'm interested in the general reasoning that goes into the design choice.

Was it helpful?

Solution

In my opinion the former makes more sense if there's not much you can sensibly do without knowing whether you have an A or B. If you wanted to unconditionally get the string with the former declaration, you'd end up with redundant cases in the pattern match. Of course, you could easily write a function to do it.

I would imagine the latter is easier for other .NET languages to work with since they lack pattern matching, but you can fake it well enough in C# using named arguments and lambda expressions.

Disclaimer: I've never coded in F# but I'm familiar with Standard ML, which is related (through OCaml).

Licensed under: CC-BY-SA with attribution
scroll top