3 ms·
It should be noted that the -- to use the terminology of the article -- extrinsically safe example module Data.List.NonEmpty.Newtype can be converted into an in
by runeks 6y ago
It should be noted that the -- to use the terminology of the article -- extrinsically safe example module Data.List.NonEmpty.Newtype can be converted into an intrinsically safe one by changing the definition of the NonEmpty type from
newtype NonEmpty a = NonEmpty [a]
to:
newtype NonEmpty a = NonEmpty (a, [a])
(and changing the associated functions accordingly -- which can now be implemented without the use of error).
EDIT: Upon further thought, I'm not sure the above distinction makes sense. The implementation of e.g. Data.List.NonEmpty.Newtype.head would still involve the use of "error" through the use of Data.List.head:
head :: NonEmpty a -> a
head (NonEmpty (x, [])) = x
head (NonEmpty (_, lst)) = Data.List.head lst
- ImprobableTruth 6y agoWhy would you use Data.List.head rather than just matching on lst?
- runeks 6y agoI realized the example doesn't make sense for head, since head should always just return the first item of the tuple. I still think it would make sense to define e.g. last using Data.List.last: last :: NonEmpty a -> a last (NonEmpty (a, [])) = a last (NonEmpty (_, lst)) = Data.List.last lst which is safe even though Data.List.last contains error.
- ImprobableTruth 6y agoYou can avoid the error of Data.List.last by 'inlining' it (just like you could in your first example) last :: NonEmpty a -> a last (NonEmpty (a, [])) = a last (NonEmpty (a, x:[])) = x last (NonEmpty (a, x:xs)) = last (NonEmpty (a, xs))
- runeks 6y agoI see your point. But I’d argue that you avoid it in both cases, since without inlining the error-call is unreachable anyway.
- chriswarbo 6y agoThat's the implementation used in previous posts, like 'parse, don't validate'. This post is talking about using newtypes instead (which seems like a worse choice in the case of NonEmpty, but may be more pragmatic when a correct-by-construction approach would be infeasable)