I have defined a data type like this for representing a 2D point:
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
data Curve = Curve [Point] deriving (Show)
How can I set the Curve datatype to be nonempty? so that it always needs to have at least 1 Point in the list?
The Data.List.NonEmpty
module, in the popular semigroups
library, implements a non-empty list type, and utility functions for it.
The solution is effectively the same as Cactus' answer, a pair that contains an obligatory first element and then a list for the rest:
data NonEmpty a = a :| [a]
So Cactus' Curve
type would be equivalent to NonEmpty Point
.
列表[Point]
将始终包含0或更多Point
s,因此如果存储额外的一个,则得到1 +(0或更多)= 1或更多 Point
s:
data Curve = Curve Point [Point]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.