1

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?

4
  • 4
    One easy way is data Curve = Curve Point [Point]. Besides, for performance reasons, you could use newtype instead of data to define Point. Commented Sep 3, 2015 at 20:58
  • 4
    Existing types defined the way @Jubobs suggested: NonEmpty, T (haddock warning: Thielemann), NonEmpty. Commented Sep 3, 2015 at 21:02
  • @DanielWagner, why does Henning merit a warning? Is there something wrong with his libraries that I haven't noticed? Commented Sep 4, 2015 at 2:30
  • 3
    @dfeuer The haddocks are very hard to read because every type is named T and every class is named C. In code, that's fine, because his style is to import everything qualified (so things look like NonEmpty.T or Ring.C), but haddock doesn't really deal with that style gracefully, resulting in type signatures that look like (C a, C b) => T a -> T b -> T -> T and other such illegible nonsense. Commented Sep 4, 2015 at 3:09

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The list [Point] will always contain 0 or more Points, so if you store an extra one, you get 1 + (0 or more) = 1 or more Points:

data Curve = Curve Point [Point]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.