[Haskell-beginners] Custom type classes

Guillaume Bouchard guillaum.bouchard+haskell at gmail.com
Wed Jan 27 00:23:52 UTC 2016


May I suggest using FunctionalDependencies

https://wiki.haskell.org/Functional_dependencies

The class declaration is changed to

class Indexable idx a | idx -> a where
    first :: idx -> a

This just means that *a* is fully determined by idx (your tuple).

Hence, instead of using as suggested

first $ Tuple3 (1::Int) 'a' False::Int

You can simplify and let the inference do its magic and use:

first $ Tuple3 1 'a' False

On Mon, Jan 25, 2016 at 8:42 AM, Imants Cekusins <imantc at gmail.com> wrote:
> Hello Daniel,
>
> it works with these tweaks:
>
> -- begin
>
> {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}
> module TupInst where
>
>
> data Tuple3 a b c = Tuple3 a b c deriving (Show)
>
> data Tuple2 a b = Tuple2 a b deriving (Show)
>
> class Indexable idx a where
>    first :: idx -> a
>
>
> instance Indexable (Tuple2 a b) a where
>    first (Tuple2 a0 b0) = a0
>
>
> instance Indexable (Tuple3 a b c) a where
>    first (Tuple3 a0 b0 c0) = a0
>
> -- end
>
> call it in ghci like this:
>
> first $ Tuple3 (1::Int) 'a' False::Int
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners


More information about the Beginners mailing list