Skip to content

Lazy toTitle capitalises letters at chunk boundaries #721

Closed

Description

@swinilohani616-dot

I noticed that lazy toTitle gives different results depending on how the text is split into chunks.
If a chunk boundary lands in the middle of a word, the letter right after it gets capitalised:

>>> :set -XOverloadedStrings
>>> import qualified Data.Text as T
>>> import qualified Data.Text.Lazy as TL
>>> TL.toTitle (TL.fromChunks ["hel", "lo wor", "ld"])
"HelLo WorLd"
>>> T.toTitle "hello world"
"Hello World"

It shows up without fromChunks too, because <> on lazy text keeps the chunks separate:

>>> TL.toTitle ("hel" <> "lo world")
"HelLo World"
>>> TL.toTitle "hello world"
"Hello World"

That's the same text giving two different answers. With lazy IO or Builder output you don't really
control where the chunks end up, so this can be surprising.

Looking at the code, lazy toTitle runs the strict one on each chunk separately:

toTitle = foldrChunks (\chnk acc -> Chunk (T.toTitle chnk) acc) Empty

The strict version always treats the start of its input as the start of a word, so each new chunk starts
a "new word". I think the fix is to carry the "are we inside a word" flag over from one chunk to the next.

I can reproduce it with text-2.1.3 on GHC 9.10.3, and on current master. I'm happy to work on a fix if
that sounds good to you.

Activity

  1. Lysxia commented on Nov 19, 2026

    @Lysxia
    Contributor

    I'm impressed this wasn't caught by tests, or is there just no test for lazy toTitle?

    A fix would be welcome!

  2. swinilohani616-dot commented on Nov 19, 2026

    @swinilohani616-dot
    ContributorAuthor

    I'm impressed this wasn't caught by tests, or is there just no test for lazy toTitle?

    A fix would be welcome!

    Thanks! It turns out there just wasn't a test for lazy toTitle. toUpper, toLower and toCaseFold each have a lazy property, but toTitle only had strict ones. Those other three work on one character at a time, so mapping them over chunks is fine. toTitle is the only one that depends on the previous character, so it's the only one the chunking breaks.

    I've opened #722 with a fix. It also adds a property that lazy toTitle matches strict toTitle on the same text, using the existing Arbitrary instance, which already splits lazy text into random chunks, so this can't slip through again.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions