NonEmptyArray?
justinwoo opened this issue ยท 11 comments
While most of the time we use NonEmptyList, there are some times we need either a NonEmpty Array or would have a use for NonEmptyArray.
Probably there would not be much more than a copy of NonEmptyList for arrays and then a few convenience functions like Array a -> Maybe (NonEmptyArray a)?
Is the idea that we want the runtime representation to be identical to that of Array a?
(Except that it cannot be empty, of course)
On Module Test.QuickCheck.Gen you can find
elements :: forall a. NonEmpty Array a -> Gen a
So yeah, should be same as Array a but NonEmpty
I'm trying to understand exactly what it is that's missing / can't be provided by the existing NonEmpty Array type; that doesn't yet seem clear.
I'm just after a few convenience utilities and the utility of having access to the various typeclass instances NonEmptyList provides, e.g. applicative, semigroup. Would make usage easier for doing stuff like exposing a NonEmptyArray of errors from Validation and such.
NonEmptyList is a newtype of NonEmpty List that provides some of those instances โ๏ธ, and also common operations like cons that involve shuffling things between the NonEmpty and List part, I assume it's just the same thing here.
It's not something I'd use personally (poor performance due to the "array cons problem"), but I can see why it might be wanted.
Since converting between NonEmpty Array and Array is O(n), perhaps it would make sense to define a NonEmptyArray type which is just a newtype over Array instead, then? So you just have to check length when converting from Array to NonEmptyArray, and the conversion in the other direction is just unwrapping it?
I just ran into a situation where I could use this. If there are no other takers, I'm happy to give it a shot.
I think Harry's idea to enforce the invariant but not do it with NonEmpty directly sounds like a good way to do it too. Missed that message earlier ๐
cross-referencing this here: #112