by kowalgta · 6y ago · 0 comments
This works great with "makes illegal states unrepresentable" approach. It helps to reduce a need for boring unit tests and lets you focus more on expressing domain in code directly.
I kind of can do it for Strings by doing something like this
type ValidStrings = 'name' | age | 'dob';
The easy way around this is a function to determine this function greaterThan2(num) return num > 2;
but it'd be cool to express this level of dynamism as a type.Smart constructor technique works well with 'parse, don't validate' approach [0]. You can push type construction to the boundries of your system so that you can work on a domain code with more precise types. It's not always so rosy however as too much types can become a burden.
[0] https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...
(* GreaterThanTwo.fsi *)
type t
val make : int -> t option
val to_int : t -> int
(* GreaterThanTwo.fs *)
type t = Value of int
let make int = if int > 2 then Some (Value int) else None
let to_int (Value int) = int
Now, `GreaterThanTwo.make x` gives you a value of type `GreaterThanTwo.t option`, meaning it can be `Some` value or `None`. If it's `Some` value, that means it really does contain an int greater than two and you can get that int using `GreaterThanTwo.to_int`.