Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type level indicator function for a type class in Haskell

For my nefarious and mostly incomprehensible reasons, I've decided to want a type level function that would indicate presence of type class instance for a type. It would work like this:

 > :kind! HasClass Show Int
 > 'True
 > :kind! HasClass Monoid Int
 > 'False

Given the Constraint types etc. added to GHC lately, I have a feeling that this might be possible, but no tidy implementation comes to mind. Can it be done?

like image 825
aleator Avatar asked Mar 04 '14 06:03

aleator


People also ask

What do you mean by type class in Haskell?

Type Classes are a language mechanism in Haskell designed to support general overloading in a principled way. They address each of the concerns raised above. They provide concise types to describe overloaded functions, so there is no expo- nential blow-up in the number of versions of an overloaded function.

How do you check types in Haskell?

If you are using an interactive Haskell prompt (like GHCi) you can type :t <expression> and that will give you the type of an expression. e.g. or e.g.

How does Haskell infer types?

Types are infered using a process generally called unification. Haskell belongs to the Hindley-Milner family, which is the unification algorithm it uses to determine the type of an expression. If unification fails, then the expression is a type error.

What are function types in Haskell?

Functions can also be passed as arguments or returned (as we have seen). Their types are given in the type signature. *Main> :t map map :: (a -> b) -> [a] -> [b] *Main> :t filter filter :: (a -> Bool) -> [a] -> [a] flip_args :: (a -> b -> c) -> b -> a -> c flip_args f x y = f y x.


1 Answers

Why not just this?

class HasClass (c :: * -> Constraint) a where
  type Has c a :: Bool

instance HasClass c a where
  type Has c a = 'False

instance (c a) => HasClass c a where
  type Has c a = 'True

Provided you don’t mind a few extensions:

{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
like image 161
Jon Purdy Avatar answered Sep 27 '22 17:09

Jon Purdy