且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一种在Haskell中分解多个类型类的简洁方法?

更新时间:2023-11-18 18:00:46

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

这定义了所需的NiceFloating :: * -> Constraint.

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?

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

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