• hallettj@leminal.space
      link
      fedilink
      English
      arrow-up
      4
      ·
      2 days ago

      If the return type of a function is NonEmpty the value returned is guaranteed to be non-empty because it is not possible to construct an empty NonEmpty value. That’s the “make illegal states unrepresentable” mantra in action.

      At runtime you might get a list from an API response or something, and it might be empty. At that point you have a regular list. Following the advice from the article you want to parse that data to transform it into the types representing your legal states. So if the list is not supposed to be empty then somewhere you have a function that takes the possibly-empty list, and returns a value of type NonEmpty. But if the list actually is empty that function will fail so it has to be able to return or throw an error. The article uses the Maybe type for that which is one of the Haskell types for functions that can fail.

      Once you have parsed the input list, and successfully gotten a NonEmpty value the rest of your code can safely access the first element of the list because a value of that type is guaranteed to have at least one value.