[Haskell-cafe] Type Directed Name Resolution

Michael Snoyman michael at snoyman.com
Thu Nov 11 08:50:32 EST 2010


On Thu, Nov 11, 2010 at 3:10 PM, Lauri Alanko <la at iki.fi> wrote:
> On Thu, Nov 11, 2010 at 03:17:39PM +0200, Michael Snoyman wrote:
>> data PetOwner
>> data FurnitureOwner
>>
>> data Cat = Cat { owner :: PetOwner }
>> data Chair = Chair { owner :: FurnitureOwner }
>
> These are clearly related uses, so as I said, you can use a type class
> to overload the accessor name in a controlled fashion.
>
>
> {-# LANGUAGE EmptyDataDecls, MultiParamTypeClasses, FunctionalDependencies #-}
>
> data PetOwner
> data FurnitureOwner
>
> data Cat = Cat { catOwner :: PetOwner }
> data Chair = Chair { chairOwner :: FurnitureOwner }
>
> class Owned a b | a -> b where
>  owner :: a -> b
>
> instance Owned Cat PetOwner where
>  owner = catOwner
>
> instance Owned Chair FurnitureOwner where
>  owner = chairOwner
>
>
> (You can also use associated type families for the same effect.)

Well, it's not exactly the same. For example:

myCat = Cat { owner = michael }

versus

myCat = Cat { catOwner = michael }

Not to mention that with TDNR, there is much less typing involved: no
need to declare a type class, declare instances, export the type
class.

Michael


More information about the Haskell-Cafe mailing list