[Haskell-cafe] Please add a method for optimized concat to the Semigroup class

Yitzchak Gale gale at sefer.org
Tue May 3 14:16:54 CEST 2011


Stephen Tetley wrote:
>> Does it have an obvious default implementation, bearing in mind it we
>> might really want a total function?
>>
>> sconcat []     = error "Yikes - I wish this was total!"
>> sconcat [a]    = a
>> sconcat (a:as) = a <> sconcat as

Holger Siegel wrote:
> You have to provide the "neutral" element by yourself:
> a <>> [] = a
> a <>> (b:bs) = a <> b <>> bs

Yes, I think that would be the best interface.

At first glance, one would be tempted to do something
like returning a Maybe, as is often done in these kinds
of cases. But here, the whole point of Semigroup is that
we don't know what to do when the list is empty, so getting
a Nothing result in that case is unhelpful.

To illustrate the point, let's look at the conversion between
those two approaches:

sconcatNonempty x xs = fromJust . sconcat $ x : xs

sconcatMaybe (x:xs) = Just $ sconcat x xs
sconcatMaybe _      = Nothing

I would much rather write sconcatMaybe when needed
than to have to write unsafe code like sconcatNonempty.

Presumably it's actually safe, since you would expect
implementations to provide a result whenever the list
is non-empty. But the type no longer provides that
guarantee.

Thanks,
Yitz



More information about the Haskell-Cafe mailing list