[Haskell-cafe] accessing a type variable in instance declaration

Roman Cheplyaka roma at ro-che.info
Wed May 22 16:40:31 CEST 2013


* TP <paratribulations at free.fr> [2013-05-22 16:18:55+0200]
> Hi all,
> 
> I wonder if there is some means to get a type variable value in the body of 
> a class instance definition. It seems it is not possible (a workaround has 
> already been given on this list), but I would like a confirmation.
> For example, imagine that I have a Tensor type constructor, that takes a 
> type-level integer (representing the Tensor order) to make a concrete type:
> 
> ---------
> instance Show (Tensor order) where
>      show TensorVar str = show "tensor " ++ str ++ " of order "
>                                     ++ (show (c2num order))
> ----------
> 
> where c2num transforms a type-level integer to an integer, through 
> typeclasses (see 
> http://www.haskell.org/haskellwiki/The_Monad.Reader/Issue5/Number_Param_Types)
> 
> I obtain a compilation error: order is not known in the body of the 
> instance. Putting ScopedTypeVariable as extension does not change anything 
> (http://www.haskell.org/ghc/docs/7.0-latest/html/users_guide/other-type-extensions.html#scoped-type-variables).

You are confusing type and value variables.

  c2num order

means apply the function 'c2num' to the value variable 'order', which is
not defined.

To get from a type to a value you can use a type class 'Sing' (for 'singleton')

  class Sing a where
    sing :: a

  instance Sing Zero where
    sing = Zero

  instance Sing a => Sing (Succ a) where
    sing = Succ sing

After adding the appropriate constraint to the instance, you can write
  
  show $ c2num $ (sing :: order)

Roman



More information about the Haskell-Cafe mailing list