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

24 views
Skip to first unread message

David Fox

unread,
Jun 19, 2016, 7:01:09 PM6/19/16
to Haskell Cafe
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...

Edward Z. Yang

unread,
Jun 19, 2016, 7:23:36 PM6/19/16
to David Fox, Haskell Cafe
A RULE could work. Assuming fromListLike is inlined, a rule can
detect when (fromList . toList :: a -> a) and then replace it with id.

edward

Excerpts from David Fox's message of 2016-06-19 16:01:01 -0700:

_______________________________________________
Haskell-Cafe mailing list
To (un)subscribe, modify options or view archives go to:
http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
Only members subscribed via the mailman list are allowed to post.

David Fox

unread,
Jun 20, 2016, 9:04:27 AM6/20/16
to Edward Z. Yang, Haskell Cafe
Wow, I had no idea that existed!
Reply all
Reply to author
Forward
0 new messages