[Haskell-cafe] class-instance

Henning Thielemann lemming at henning-thielemann.de
Thu Jan 20 21:46:42 CET 2011


> On 20/01/2011 18:56, Ryan Ingram wrote:
>> On Wed, Jan 19, 2011 at 11:56 PM, Patrick Browne <patrick.browne at dit.ie> wrote:
>>> I am trying to see what how this requirement can be represented using
>>> just the normal instance-implements-class relation for a comparison with
>>> a specification language approach.
>>>
>>> If there is no simple way to do this using type classes then I am
>>> obviously mis-using the technique.
>> Going back to your original message:
>>
>> -- My intension is that the PERSON class should *specify*
>> -- that a person has a constant id called p1
>> -- and that a person has a name that can be found from the id.
>>
>> You can do this with type level numerals.
>>
>> data Z
>> data S a
>>
>> type Zero = Z
>> type One = S Zero
>> type Two = S One
>> -- etc
>>
>> class PersonId a where
>>     name :: a -> String
>>
>> instance PersonId Z where
>>     name _ = "John"
>> instance PersonId (S Z) where
>>     name _ = "Julie"
>>
>> main = putStrLn (name (undefined :: One))  -- prints "Julie"


Do the ids need to be numbers? You could also define

data John
data Julie

instance PersonId John where
    name _ = "John"

instance PersonId Julie where
    name _ = "Julie"




More information about the Haskell-Cafe mailing list