一种在Haskell中分解多个类型类的简洁方法? [英] A concise way to factor out multiple typeclasses in Haskell?

查看:51
本文介绍了一种在Haskell中分解多个类型类的简洁方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Haskell代码库中,我有许多采用多态参数的函数.这些多态参数都需要满足相同的类型类集(RealFloat a, Floating a, Real a, Show a, Ord a, Typeable a),并且这些类型类集必须存在于函数的类型注释中.

现在我一直在为每个函数手动编写typeclass注释,但是在我的代码库中重复列出该类型类30次以上变得很冗长,而且如果我发现我必须更改每个类型注释,也很麻烦需要向列表添加另一个类型类.我想知道是否有一种更简洁的方法来排除常见的类型类列表.

我真的想定义一个像typeclass NiceFloating a = RealFloat a, Floating a, Real a, Show a, Ord a, Typeable a这样的类型类同义词",所以我可以在所有类型注释中写NiceFloating a => a.

如果该功能不存在,也许我可以编写一个主类型类",要求一个值满足类型类列表中的每个类型类?但是我不想写出所有的操作例如手动进行显示",显示"和"Ord"操作-有解决的办法吗?

解决方案

{-# 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.

这篇关于一种在Haskell中分解多个类型类的简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆