re: Use opaque types in Elm! VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Then the create function does multiple things For instance we have function which get 2 numbers and return sum of them. The first number is odd a...

Opaque types allow to capture guarantees and propagate them. If you only need these guarantees on a specific part of your code and there is no need to propagate them, then it is probably not worth it to create opaque types for them. In other words, not every "validation check" should result in an opaque type.

However, most of the time this is an API design choice. For instance, I would understand this API better than the example you provided:

type Odd = Odd Int
type Even = Even Int

oddFromInt : Int -> Maybe Odd
evenFromInt : Int -> Maybe Even
sum : Odd -> Even -> Odd

The advantages here are:

  • We move potential errors closer to their cause (conversions).
  • We keep sum error-free! We can call it multiple times without having to deal with errors: sum (sum odd even) even
  • We specify that the returned sum value is guaranteed to be an Odd number.
code of conduct - report abuse