Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A concise way to factor out multiple typeclasses in Haskell?

In my Haskell codebase, I have many functions that take polymorphic arguments. These polymorphic arguments all need to satisfy the same set of typeclasses (RealFloat a, Floating a, Real a, Show a, Ord a, Typeable a) and this set of typeclasses needs to be present in the functions' type annotations.

Right now I've been manually writing the typeclass annotations for every function, but it gets verbose to have that list of typeclasses repeated 30+ times in my codebase, and cumbersome to have to change each type annotation if I find out I need to add another typeclass to the list. I'm wondering if there is a more concise way to factor out a common list of typeclasses.

I'm really looking to define a "typeclass synonym" like typeclass NiceFloating a = RealFloat a, Floating a, Real a, Show a, Ord a, Typeable a so I can just write NiceFloating a => a in all of my type annotations instead.

If that feature doesn't exist, perhaps I can write a "master typeclass" that requires that a value satisfy every typeclass in the list of typeclasses? But I don't want to write out all the operations for e.g. Real, Show, and Ord by hand—is there a way around that?

like image 202
kye Avatar asked Feb 05 '18 21:02

kye


1 Answers

{-# LANGUAGE ConstraintKinds #-}
type NiceFloating a = (RealFloat a, Floating a, Real a, Show a, Ord a, Typeable a)

This defines the wanted NiceFloating :: * -> Constraint.

like image 126
chi Avatar answered Nov 14 '22 04:11

chi