3 ms·
Pop an item from an array. What do you return when the array is empty? Solution: nil. Problem: How do you tell the difference between "the array was empty" and
by edflsafoiewq 7y ago
Pop an item from an array. What do you return when the array is empty?
Solution: nil. Problem: How do you tell the difference between "the array was empty" and "the item you popped was nil"?
Solution: have pop return a Maybe instead.
- alaaalawi 7y agoor allow returning multiple values. for example in CL searching for a thing returns two values the is-found and the value
- uryga 7y ago...which, btw, is equivalent to Maybe/Either – they're tagged unions, i.e. pairs (tag, content). Maybe<T> is isomorphic* to { has_value: bool, val: T|nil } * well, this representation is a bit too permissive, since you could do {has_value: true, val: nil} if you wanted to get the types water-tight, you'd need dependent types, typing it as dependent pair: Maybe<T> = sigma (has_value: bool) if has_value then T else () which can then only have values (false, ()) or (true, <actual value of type T>)
- coldtea 7y agoWhich is the same thing, but in an ad-hoc way, and leaves it open to the developer to check or not, and thus to crash.
- inopinatus 7y agoor solution: Null Object or a whole value or use an enumerator or a collection decorator All of which are simple solutions already available. No need to import every new paradigm hammer in the hope that everything is a nail.