Haskell 数据声明中的类型约束 [英] Type Constraints in Data Declaration Haskell

查看:17
本文介绍了Haskell 数据声明中的类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Haskell 并尝试编写以下内容:

I'm using Haskell and trying to write the following:

data Scale s = Scale s s

然而,我想让 s 必须是 Num 类型类的东西,比如 Int 或 Double.使用 Haskell 和 GHC 可以做到吗?

However, I want to make it so that s must be something that of the Num type class, like Int or Double. Is that possible to do using Haskell and GHC?

推荐答案

是:

{-# LANGUAGE GADTs #-}
data Scale s where
    Scale :: Num s => s -> s -> Scale s

但是,通常认为最好的做法是这样做.相反,将 Num 约束仅放在使用 Scaleneed Num 约束的函数上.对这些约束放宽可以让你在适当的时候暂时打破不变量;例如对于这样的类型,通常希望有一个 Functor 实例,如果你像上面那样约束构造函数,这是不可能的.

However, it's generally considered best practice not to do this. Instead, put the Num constraint only on the functions that use Scales and need the Num constraint. Being relaxed about such constraints allows you to temporarily break the invariant where appropriate; e.g. it's common to wish for a Functor instance for such a type, which is impossible if you constrain the constructor as above.

这篇关于Haskell 数据声明中的类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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