Compound Data

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import sys
import unittest
from dataclasses import dataclass
from typing import *
sys.setrecursionlimit(10**6)

## Compound data is represented by product types: in Python
## these are written as classes.

@dataclass(frozen=True)
class Student:
    id : str
    preferred_name : str
    birth_year : int


# examples of data
s1 = Student("uhooth","Uhoh Hoothn",2006)
s2 = Student("htonso","Hans Tonsorio",2012)

# return the student with the alphabetically earlier id.
# signal an error if the two students have the same id.
def id_earlier(s1 : Student, s2 : Student) -> Student:
    if (s1.id < s2.id):
        return s1
    elif (s1.id == s2.id):
        raise ValueError('expected students with different ids, got {} and {}'
                         .format(s1,s2))
    else:
        return s2


class MyTests(unittest.TestCase):
    def test_id_less_than(self):
        self.assertEqual(s2,id_earlier(s2,s1))
        self.assertEqual(s2,id_earlier(s1,s2))
        with self.assertRaises(ValueError):
            id_earlier(s1,s1)