Skip to content

Add a function to split text at the first occurrence of a character #625

Open

Description

@vsannier

I was surprised not to find a function in the library to split a text on the first match of a character/text/predicate, with the matched part discarded.
This is not difficult to write using breakOn and drop, but I think a function implemented with the internals of the library might have better performance.

split1 :: Char -> Text -> (Text, Text)
split1 c = (id *** drop 1) . (breakOn $ singleton c)

See a similar function (previously called splitOnce) in the byteslice package, and a question on Stack Overflow about splitAtfirst.

Activity

  1. Bodigrim commented on Jan 13, 2025

    @Bodigrim
    Contributor

    IMHO split1 c = fmap (drop 1) . break (== c) is short enough and does not suffer from any significant performance penalty: drop 1 is constant-time, negligible in comparison to the linear time of break.

    Note that the function from byteslice has a different signature, with Maybe.

  2. sol commented on Apr 5, 2025

    @sol
    Member

    @Bodigrim comparing

    split1 c = fmap (drop 1) . (breakOn $ singleton c)

    vs

    split1 c = fmap (drop 1) . break (== c)

    The first option, using breakOn, should be significantly faster than the second option, no?

    Rational:

    breakOn can look at the needle and choose the optimal strategy (specifically if c is in the ASCII range, it can just do a sequential scan).

    break on the other hand always needs to decode to Char.

  3. sol commented on Apr 5, 2025

    @sol
    Member

    Corresponding code:

    indices :: Text -- ^ Substring to search for (@needle@)
    -> Text -- ^ Text to search in (@haystack@)
    -> [Int]
    indices needle@(Text narr noff nlen)
    | nlen == 1 = scanOne (A.unsafeIndex narr noff)
    | nlen <= 0 = const []
    | otherwise = indices' needle
    {-# INLINE indices #-}

    scanOne :: Word8 -> Text -> [Int]
    scanOne c (Text harr hoff hlen) = loop 0
    where
    loop !i
    | i >= hlen = []
    | A.unsafeIndex harr (hoff+i) == c = i : loop (i+1)
    | otherwise = loop (i+1)
    {-# INLINE scanOne #-}

  4. Bodigrim commented on Apr 5, 2025

    @Bodigrim
    Contributor

    @sol yes, I'd expect breakOn to be faster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions