Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out which (concrete) types satisfy a set of typeclass constraints?

Given a number of typeclass constraints:

{-# LANGUAGE ConstraintKinds, MultiParamTypeClasses #-}
import Data.Array.Unboxed(Ix,IArray,UArray)

type IntLike a = (Ord a, Num a, Enum a, Show a, Ix a, IArray UArray a)

How can I find out which types satisfy IntLike, i.e. all the mentioned constraints jointly?

I can puzzle together the information needed from the output of ghci's :info command, and then doublecheck my work by calling (or having ghci typecheck)

isIntLike :: IntLike -> Bool
isIntLike = const True

at various types, e.g. isIntLike (3::Int).

Is there a way to get ghci to do this for me?

I'm currently interested in concrete types, but wouldn't mind having a more general solution which also does clever stuff with unifying contexts!

like image 797
yatima2975 Avatar asked Oct 29 '14 08:10

yatima2975


People also ask

How do you find type 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.

Can Haskell lists have different types?

Haskell also incorporates polymorphic types---types that are universally quantified in some way over all types. Polymorphic type expressions essentially describe families of types. For example, (forall a)[a] is the family of types consisting of, for every type a, the type of lists of a.

What is a type class dictionary?

Type classes define interfaces that in Haskell's terms are called dictionaries. For instance, from the Ord class definition the compiler will create a dictionary that stores all the class methods.

What is the difference between type and data in Haskell?

Type and data type refer to exactly the same concept. The Haskell keywords type and data are different, though: data allows you to introduce a new algebraic data type, while type just makes a type synonym. See the Haskell wiki for details.


1 Answers

Community Wiki answer based on the comments:

You can do this using template haskell.

main = print $(reify ''Show >>= stringE . show).

This won't work for type synonyms - rather, reify returns the AST representing the type synonym itself, without expanding it. You can check for type synonyms which are constraints, extract the constraints of which that type synonym consists, and continue reifying those.

like image 92
sclv Avatar answered Oct 15 '22 12:10

sclv