数据声明Haskell中的类型约束 [英] Type Constraints in Data Declaration 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
约束仅放在使用Scale
s和需要 Num
约束的函数上.放宽对此类约束的限制,使您可以在适当的时候暂时打破不变式.例如通常希望为这种类型的Functor
实例,如果按上述约束构造函数,则是不可能的.
However, it's generally considered best practice not to do this. Instead, put the Num
constraint only on the functions that use Scale
s 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屋!