[Haskell-cafe] Foldable intercalate for Data.Text?

Viktor Dukhovni ietf-dane at dukhovni.org
Sun Jan 22 03:34:44 UTC 2023


On Sat, Jan 21, 2023 at 07:49:15PM -0500, Viktor Dukhovni wrote:

> I rather think it is simply a direct analogue of `intercalate` for
> Strings (i.e. Lists).  The natural API for folding containers to Text is
> Text builders:
> 
>     import Data.Text.Lazy.Builder
> 
>     buildCalate :: Foldable f
>                 => (a -> Builder)
>                 -> Builder
>                 -> f a
>                 -> Builder
>     buildCalate f sep1 = snd . foldr go (mempty, mempty)
>       where
>         go e (sep, r) = (sep1, f e <> sep <> r)

But the above was hastily written, and came out too strict in the tail,
the correct form is:

    buildCalate :: Foldable f
                => (a -> Builder)
                -> Builder
                -> f a
                -> Builder
    buildCalate f sep = snd . foldr go (mempty, mempty)
      where
        go x ~(s, r) = (sep, f x <> s <> r)

we need to obtain the next separator without forcing the rest of the
fold.

-- 
    Viktor.


More information about the Haskell-Cafe mailing list