简体   繁体   English

定义新的Haskell类型

[英]Defining a new haskell type

I'm new to haskell. 我是Haskell的新手。 I've two questions but they're somewhat related. 我有两个问题,但它们有些相关。

Is it possible to define a type of Integers excluding specific integers for example zero. 是否可以定义一种类型的整数,但不包括特定的整数(例如零)。 Or just positive numbers. 或者只是正数。

data allIntsButZero = ..? { a /= 0 | for all a in Int} ??
data positiveInts   = ..? { a >= 0 | for all a in Int} ??

In short, can I define a type as a subset of another type? 简而言之,我可以将一种类型定义为另一种类型的子集吗?

Secondly, can i define a type where there is a logic imposed? 其次,我可以定义施加逻辑的类型吗? eg 例如

type doublePair = (Int, Int * 2) {- where snd is always 2 times of fst -}
data validDDMMYYYY = G Int Int Int {- where complies to gregorian calendar -}

The type doublePair of these really doesn't make sense. 这些type doublePair确实没有任何意义。 If the snd is always twice the fst , then it doesn't actually contain any information! 如果snd始终是fst两倍,那么它实际上不包含任何信息! So, this type is definitely better expressed as 因此,这种类型肯定更好地表示为

newtype DoubleableInt = DoubleableInt {getDoubleableInt :: Int}

The others do make some sense, but I think you're still a bit missing the point of an abstraction . 其他的也确实有道理,但是我认为您仍然缺少抽象的意义 The type validDDMMYYYY is probably supposed to express a date , ie a point in time. 类型validDDMMYYYY可能应该表示一个日期 ,即一个时间点。 How it respresents this shouldn't really be the user's concern: if a library depends on a certain representation, it should simply should offer specialised “smart constructors” to ensure well-formedness. 它是如何respresents这个真的不应该是用户的担忧:如果一个库依赖于一定的代表性,它应该简单地应该提供专门的“智能构造函数”,以确保良好性。 Like 喜欢

newtype AllIntsButZero = AllIntsButZero {getNonzeroInt :: Int}

mkNonzeroInt :: Int -> Maybe AllIntsButZero
mkNonzeroInt 0 = Nothing
mkNonzeroInt n = AllIntsButZero n

You may then refuse to export the AllIntsButZero constructor (which would allow users to form incorrect AllIntsButZero 0 ): 然后,您可以拒绝导出AllIntsButZero构造函数(这将允许用户形成不正确的AllIntsButZero 0 ):

module RestrictedNumbers (AllIntsButZero, getNonzeroInt, mkNonzeroInt) where

This way, users will only see AllIntsButZero as a “black box”, and the functions they can use with it are guaranteed to yield well-formed values. 这样,用户只会将AllIntsButZero视为“黑匣子”,并且可以与它们一起使用的函数可以保证产生格式正确的值。

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

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