purescript/purescript-strings

`split` should return a NonEmptyArray?

JamieBallingall opened this issue · 3 comments

Is there ever an occasion when Javascript's String.prototype.split() returns an empty array? If not, couldn't we have split :: Pattern -> String -> NonEmptyArray String? Or another version, called split', if we want to avoid breaking changes.

Should split be upgraded to return a non-empty array, or should we implement split' :: Pattern -> String -> NonEmptyArray String? The underlying Javascript function String.prototype.split() will return an empty array if the input to be split is an empty string. So an implementation might look like:

split' :: Pattern -> String -> NonEmptyArray String
split' p s = fromMaybe (singleton s) (fromArray $ split p s)

I guess that the original split has the property that no elements of the resulting array are empty strings, so maybe a version as split' is preferable.

I guess that the original split has the property that no elements of the resulting array are empty strings

This is the main reason why split can't return a NonEmptyArray, though it could return a Maybe (NonEmptyArray String). Still, that's isomorphic to Array String, and you can always get the same thing by calling NonEmptyArray.fromArray on the result of split.

You could argue that there should be a split :: Pattern -> NonEmptyString -> NonEmptyArray String, though!

There's a splitAt, but no split that I can see.

splitAt
:: Int
-> NonEmptyString
-> { before :: Maybe NonEmptyString, after :: Maybe NonEmptyString }
splitAt i nes =
case CP.splitAt i (fromNonEmptyString nes) of
{ before, after } -> { before: fromString before, after: fromString after }

Due to the lack of activity here, I'm going to close this. Feel free to reopen.