this post was submitted on 06 Jan 2025
81 points (96.6% liked)
Programming
17760 readers
499 users here now
Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!
Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.
Hope you enjoy the instance!
Rules
Rules
- Follow the programming.dev instance rules
- Keep content related to programming in some way
- If you're posting long videos try to add in some form of tldr for those who don't want to watch videos
Wormhole
Follow the wormhole through a path of communities [email protected]
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
You cannot, and that's why that type declaration models a
NonEmpty
that a type checker can enforceSo it's the implementation that has to ensure a
NonEmpty
is returned, but that's up to the developer, correct? The developer still holds the gun to shoot themselves in the foot by returning an empty list, IINM.Anti Commercial-AI license
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 emptyNonEmpty
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 theMaybe
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.