Home > Net >  How do I define a "PersonList" which can store any number of "person"
How do I define a "PersonList" which can store any number of "person"

Time:10-18

In Haskell I've defined a datatype "Person". Now I want to define a List which can store any number of Persons. The goal is to be able to add an arbitrary amount of people to yet another datatype called "Class".

These are my attempts:

data Date = DMY
    Int     -- day
    Int     -- month
    Integer -- year
    deriving Show

data Person = Person
    String -- first name
    String -- last name
    Date   -- birthday
    deriving Show

data Room = 
 Room
    String  -- name of room
    Int -- capacity of students
    Bool -- computer access for students
 deriving Show

data PersonList = 
    Empty | Person PersonList
 deriving Show


data Class = 
 Lecture String Room Teacher PersonList Date
 |Lab String Room Teacher PersonList Int
 deriving Show

data Teacher = Teacher String deriving Show

CodePudding user response:

The usual way of doing this is to use the built-in list type instead of defining a separate PersonList type. So, Class would be defined using the type [Person] in place of the type PersonList, like so:

data Class
 = Lecture String Room Teacher [Person] Date
 | Lab String Room Teacher [Person] Int
 deriving Show

If you really want to define a dedicated PersonList type from scratch, it would be something like:

data PersonList =
  Empty | Node Person PersonList

That is, a "person list" is either Empty or a Node consisting of the first "person" plus the rest of the "person list". This very similar to the way the built-in list type is defined, except that the built-in type works with any element type instead of only Person elements, and there are lots of built-in functions for working with the built-in list type that you'd have to rewrite yourself if you tried to use this PersonList type.

CodePudding user response:

Just use an existing list type, like [Person] or Vector Person. There's no need to reinvent the wheel here. If you want to call it a PersonList, use a type alias:

type PersonList = [Person]

As an aside, you really should be using record syntax for complex datatypes, especially if you're going to annotate the members anyways. Your current implementation of Date, for example, requires somebody to look at the comments in the definition every time they need to understand what's happening. You can formalize those annotations in record syntax:

data Date = DMY
  { day   :: Int
  , month :: Int
  , year  :: Int -- it's unlikely you need years beyond 9223372036854775807 C.E.
  }
  • Related