A concise way to factor out multiple typeclasses in Haskell?

白昼怎懂夜的黑 提交于 2020-06-25 00:58:12

问题


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?


回答1:


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

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



来源:https://stackoverflow.com/questions/48631939/a-concise-way-to-factor-out-multiple-typeclasses-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!