core icon indicating copy to clipboard operation
core copied to clipboard

String.words and String.lines don't return empty list for blank string

Open lassik opened this issue 6 years ago • 1 comments

Currently String.words is an alias for Elm.Kernel.String.words. Likewise, String.lines is an alias for Elm.Kernel.String.lines.

These functions are defined using the JavaScript string split function as:

  • String.words: str.trim().split(/\s+/g)
  • String.lines: str.split(/\r\n|\r|\n/g)

JavaScript's string split always returns at least one substring. This means that:

  • String.words returns [""] for a zero-length or whitespace-only string.
  • String.lines returns [""] for a zero-length string.

Is this intentional? IMHO it would be more intuitive if:

  • String.words: returned the empty list [] for a zero-length or whitespace-only string.
  • String.lines: returned the empty list [] for a zero-length string. For whitespace-only strings, a more complicated approach is needed.

Currently the documentation for these functions doesn't mention these boundary cases.

lassik avatar Feb 12 '19 13:02 lassik

I just came across this regarding String.split. As far as I can tell, String.split cannot return an empty list. In my code I am doing this

fromString : String -> Maybe Route
fromString url =
    case String.split "?" url of
        path :: query :: [] ->
            -- ..    
        path :: [] ->
            -- ..
        [] ->
            -- This case is impossible

        _ -> Nothing

To me, it is intuitive that String.split "?" "" returns [""]. In the same way that I would expect String.split "?" "hello" to return ["hello"].

What if instead of returning [] in these empty string cases, it returns a non-empty list? Like ("", [])?

Chadtech avatar Jul 27 '20 21:07 Chadtech