Data
Let's start with a few examples of data declaration.
data Person
name :: String
age :: Int
what about friends?
data Person
name :: String
age :: Int
friends :: [] of Person
What if we consider animals as friends as well?
data Animal
...
data Person
name :: String
age :: Int
friends :: [] of (Person | Animal)
Can't this be shortened?
type Friends = [] of (Person | Animal)
data Person
name :: String
age :: Int
friends :: Friends
Let's say that a person can hold something in its arms. And that something could basically be anything. We could write:
data Person
name :: String
age :: Int
friends :: [] of (Person | Animal)
holding :: ?
What about the wisdom of a person?
...to simplify it, let's assume it is directly proportional to the age.
data Person
name :: String
age :: Int
friends :: Friends
holding :: ?
wisdom = 1.23 * age
In this latter example, notice that "wisdom" cannot be set. It is a "read only" property of a person data.
Now, let's say that we want to have some generic tree structure.
data Tree
content :: ?
children :: [] of Tree
...ok, but what if we want the tree to only contain people?
No problem, just make a parametrized data:
data Tree(x)
content :: x
children :: [] of Tree(x)
type PeopleTree = Tree(Person)
How to make a data value?
Person joe
name = "joe"
age = 33
friends = [jack]
holding = Nothing
Person jack
name = "jack"
age = 44
friends = [joe]
holding = Nothing
jimmy = Person("jimmy", 55, [joe,jack], Nothing)
How to access data members?
joe.name ++ "says: Hi " ++ joe.friends.(1).name ++ "!"