[Haskell-beginners] Custom type classes

Daniel Hinojosa dhinojosa at evolutionnext.com
Mon Jan 25 06:43:23 UTC 2016


Got it to work this way but it got the wrong one. Still looking.

instance Indexable (Tuple2 a) where
    first (Tuple2 b a) = a


On Sun, Jan 24, 2016 at 11:39 PM, Daniel Hinojosa <
dhinojosa at evolutionnext.com> wrote:

> Quick adjustment, playing around too much with it, that should be:
>
> class Indexable idx where
>    first :: idx a -> a
>
> Problem still exists.
>
> On Sun, Jan 24, 2016 at 11:25 PM, Daniel Hinojosa <
> dhinojosa at evolutionnext.com> wrote:
>
>> I am pretty sure I have a good handle on type classes, but this one is
>> perplexing me in Haskell.  I created custom Tuples called Tuple2 and Tuple3
>> (I know Haskell already has Tuples, just thought I would create my own for
>> this exercise). Then I wanted to create a type class that would have a
>> method called first that would get the first element of the tuple
>> regardless of what kind of Tuple it is. Tuple2, Tuple3, etc.
>>
>> Here is what I have:
>>
>> data Tuple3 a b c = Tuple3 a b c deriving (Show)
>>
>> data Tuple2 a b = Tuple2 a b deriving (Show)
>>
>> class Indexable idx where
>>    first :: idx c -> a
>>
>> instance Indexable (Tuple2 a) where
>>    first (Tuple2 a b) = a
>>
>> In my main, I try to get call putStrLn $ show $ first $ Tuple2 1 "One"
>>
>> I was greeted with the following trace:
>>     Couldn't match expected type ‘a1’ with actual type ‘a’
>>       ‘a’ is a rigid type variable bound by
>>           the instance declaration at TypeClasses.hs:35:10
>>       ‘a1’ is a rigid type variable bound by
>>            the type signature for first :: Tuple2 a c -> a1
>>            at TypeClasses.hs:36:4
>>     Relevant bindings include
>>       a :: a (bound at TypeClasses.hs:36:18)
>>       first :: Tuple2 a c -> a1 (bound at TypeClasses.hs:36:4)
>>     In the expression: a
>>     In an equation for ‘first’: first (Tuple2 a b) = a
>>
>> Help is appreciated.
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160124/07e80afb/attachment.html>


More information about the Beginners mailing list