[Haskell-cafe] class-instance

Ryan Ingram ryani.spam at gmail.com
Wed Jan 19 11:41:22 CET 2011


I don't think that's exactly what you want, though.  name (2::Int)
crashes your program.

I think you really want a data type.

data Person a b = P a b

pid :: Person a b -> a
pid (P a _) = a

pname :: Person a b -> b
pname (P _ b) = b

Now, what it looks like you want is some kind of extensible relation

name 1 = "john"
name 2 = "julie"
etc.

but there's no simple way to specify this as an open function at the
value level.  You can make a list of all the people:

people = [ P 1 "john", P 2 "julie" ]

name :: Int -> Maybe String
name x = fmap pname $ safeHead $ filter ((== x) . pid) people

safeHead [] = Nothing
safeHead (x:_) = Just x

It's still not really clear what you are trying to do.

  -- ryan

On Mon, Jan 17, 2011 at 9:15 AM, Patrick Browne <patrick.browne at dit.ie> wrote:
> A functional dependency seems to allow me to express my rather strange
> requirement.
>
> class Person i n | i  -> n where
>     pid :: i
>     name :: i -> n
>
> instance Person Int String where
>     pid = 1
>     name(1) = "john"
>
>
> -- name(pid::Int) will produce john
>
> Thanks for your help
>
> Pat
>
>
>
> On 17/01/2011 14:07, Patrick Browne wrote:
>> On 17/01/2011 13:04, Ketil Malde wrote:
>>>> So other PERSONs would have different types, say:
>>
>> I think the problem is there is just one constant p1 in the class and
>> there needs to be multiple constants in the implementation (one for each
>> person). It seems difficult to specify this using type classes So, some
>> data declaration as you suggest will probably be needed.
>>
>> Thanks,
>> Pat
>>
>>
>>
>> This message has been scanned for content and viruses by the DIT Information Services E-Mail Scanning Service, and is believed to be clean. http://www.dit.ie
>>
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
> This message has been scanned for content and viruses by the DIT Information Services E-Mail Scanning Service, and is believed to be clean. http://www.dit.ie
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>



More information about the Haskell-Cafe mailing list