[Haskell-beginners] how do typeclasses work again?

Nicholls, Mark nicholls.mark at vimn.com
Thu Feb 9 16:59:00 UTC 2017


Sorry..I do haskell about once every 6 months for 2 hours...and then get on with my life.

I always forget some nuance of typeclasses.

Consider some simple typeclass

> class Is isx x where
>   apply :: (x -> y) -> isx -> y


We can make any type a member of it...mapping to itself

> instance Is x x where
>   apply f = f

But we can also make a tuple a member of it...and pull the 1st member.. 

> instance Is (x,y) x where
>   apply f (x,y) = f x

Weird and largey useless...but I'm playing.

Then construct a function to operate on it

> foo2 :: (Is isx Integer) => isx -> String
> foo2 = apply (\i -> "")

And...

• Could not deduce (Is isx x0) arising from a use of ‘apply’
      from the context: Is isx Integer
        bound by the type signature for:
                   foo2 :: Is isx Integer => isx -> String
        at prop.lhs:51:3-43
      The type variable ‘x0’ is ambiguous
      Relevant bindings include
        foo2 :: isx -> String (bound at prop.lhs:52:3)
      These potential instances exist:
        instance Is x x -- Defined at prop.lhs:41:12
        instance Is (x, y) x -- Defined at prop.lhs:45:12
    • In the expression: apply (\ i -> "")
      In an equation for ‘foo2’: foo2 = apply (\ i -> "")


What's it going on about?
(my brain is locked in F# OO type mode) 

I've told it to expect a function "Integer -> String"...surely?
Whats the problem.

CONFIDENTIALITY NOTICE

This e-mail (and any attached files) is confidential and protected by copyright (and other intellectual property rights). If you are not the intended recipient please e-mail the sender and then delete the email and any attached files immediately. Any further use or dissemination is prohibited.

While MTV Networks Europe has taken steps to ensure that this email and any attachments are virus free, it is your responsibility to ensure that this message and any attachments are virus free and do not affect your systems / data.

Communicating by email is not 100% secure and carries risks such as delay, data corruption, non-delivery, wrongful interception and unauthorised amendment. If you communicate with us by e-mail, you acknowledge and assume these risks, and you agree to take appropriate measures to minimise these risks when e-mailing us.

MTV Networks International, MTV Networks UK & Ireland, Greenhouse, Nickelodeon Viacom Consumer Products, VBSi, Viacom Brand Solutions International, Be Viacom, Viacom International Media Networks and VIMN and Comedy Central are all trading names of MTV Networks Europe.  MTV Networks Europe is a partnership between MTV Networks Europe Inc. and Viacom Networks Europe Inc.  Address for service in Great Britain is 17-29 Hawley Crescent, London, NW1 8TT.


More information about the Beginners mailing list