[Haskell-cafe] How to avoid expensive and unnecessary type conversions?

David Fox dsf at seereason.com
Sun Jun 19 23:01:01 UTC 2016

Suppose you have a class ListLike (which you do have, actually) and it has
methods for operations on types that are like lists, and in particular it
has a method fromListLike which converts any ListLike value to any other:

    fromListLike :: ListLike full' item => full' -> full

the default implementation of this is simply

    fromListLike = fromList . toList

but this means that if you happen to apply fromListLike to a value which is
already the desired type, two unnecessary and possibly expensive
conversions take place.  My question is, how can one write code that
implements fromListLike in such a way that when the two type parameters are
the same type it just uses

    fromListLike = id

I've thought about using a class Convert a b class and writing an instance
for every pair of ListLike instances.  I haven't convinced myself this
would work, and if it does it means that adding a new instance involves
writing a bunch of Convert instances.  Maybe one could somehow have a
default implementation (fromList . toList) but then you run into
overlapping instances.  Anyone have better ideas about any of this?
Hopefully I'm missing something dead simple...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20160619/9ae3ece4/attachment.html>

More information about the Haskell-Cafe mailing list