简体   繁体   English

Haskell 数据声明中的类型约束

[英]Type Constraints in Data Declaration Haskell

I'm using Haskell and trying to write the following:我正在使用 Haskell 并尝试编写以下内容:

data Scale s = Scale s s

However, I want to make it so that s must be something that of the Num type class, like Int or Double.但是,我想让s必须是 Num 类型类的东西,例如 Int 或 Double。 Is that possible to do using Haskell and GHC?使用 Haskell 和 GHC 可以做到吗?

Yes:是的:

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

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.相反,仅将Num约束放在使用Scale需要Num约束的函数上。 Being relaxed about such constraints allows you to temporarily break the invariant where appropriate;放宽这些约束可以让你在适当的时候暂时打破不变量; eg it's common to wish for a Functor instance for such a type, which is impossible if you constrain the constructor as above.例如,通常希望有一个Functor实例用于这种类型,如果您像上面那样约束构造函数,这是不可能的。

I had a similar situation with Point type.我对Point类型有类似的情况。 But I thought not about constraints, I thought about how to do generalizing element type of my point.但我没有考虑约束,我想的是如何概括我的观点的元素类型。 Then I understood if I'll have point type like this data Point a = Point aa then I can do it instance of Functor, Applicative, Foldable and Traversable.然后我明白了如果我有这样的data Point a = Point aa点类型data Point a = Point aa那么我可以做 Functor、Applicative、Foldable 和 Traversable 的实例。 And I'll can design function by standart general way.而且我可以通过标准的通用方式设计功能。 For example:例如:

dist :: Floating a => Point a -> Point a -> a
dist a b = sqrt $ sum $ (^2) <$> ((-) <$> a <*> b)

And I had question.我有疑问。 What is going on?到底是怎么回事? :) If I add constraint (as you asked) I would not can design by this way and I would need to implement a lot of functions like pointSub . :) 如果我添加约束(如您所问),我将无法通过这种方式进行设计,并且我需要实现很多功能,例如pointSub

So, there is something to think about :)所以,有一些事情要考虑:)

What about this:那这个呢:

data Scale' s = Scale s s
type Scale = Scale' Int Int

I did not try this, I do not know Haskell that well, just (mostly) reading about it, but it seems reasonable, isn't it?我没有尝试这个,我不太了解 Haskell,只是(大部分)阅读它,但它似乎合理,不是吗? 🤔 🤔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM