[英]Haskell define a non-empty list datatype
I have defined a data type like this for representing a 2D point: 我已经定义了这样的数据类型来表示2D点:
data Point = Point (Double, Double) deriving (Show)
And a data type Curve (curve is a list of points in 2D space that create a curve 数据类型曲线(曲线是2D空间中创建曲线的点列表
data Curve = Curve [Point] deriving (Show)
How can I set the Curve datatype to be nonempty? 如何将Curve数据类型设置为非空? so that it always needs to have at least 1 Point in the list?
所以它总是需要在列表中至少有1个点?
The Data.List.NonEmpty
module, in the popular semigroups
library, implements a non-empty list type, and utility functions for it. 流行的
semigroups
库中的Data.List.NonEmpty
模块实现了非空列表类型和实用程序功能。
The solution is effectively the same as Cactus' answer, a pair that contains an obligatory first element and then a list for the rest: 解决方案实际上与Cactus的答案相同,一对包含必需的第一个元素,然后是其余的列表:
data NonEmpty a = a :| [a]
So Cactus' Curve
type would be equivalent to NonEmpty Point
. 因此仙人掌的
Curve
类型将等同于NonEmpty Point
。
列表[Point]
将始终包含0或更多Point
s,因此如果存储额外的一个,则得到1 +(0或更多)= 1或更多 Point
s:
data Curve = Curve Point [Point]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.