User Defined Types in Haskell

From point of view of python programmer.

Two kinds

Sum type in Python

class Color(Enum):
    red = 1
    green = 2
    blue = 3

Sum type in Haskell

data Color = Red | Green | Blue
"data" TypeName "=" Constructor [ ("|" Constructor) ]

Product type in Python

class Person(object):
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

Product type in Haskell

-- | Person Name Surname
data Person = Person String String
"data" TypeName "=" Constructor [ ArgumentType ]

Product type in Haskell

data Person = Person Name Surname

type Name    = String
type Surname = String

Accessing attributes

name :: Person -> Name
name (Person n _) = n

Record syntax

data Person = Person
            { name    :: Name
            , surname :: Surname
            }

Every type is Sum Type

data Tree = Empty
          | Leaf a
          | Node Tree Tree

The same tree in python

class Tree(object): pass

class Empty(Tree):  pass

class Leaf(Tree):
    def __init__(self, value):
        """
        :type value: object
        """
        self.value = value

class Node(Tree):
    def __init__(self, c1, c2):
        """
        :type c1: L{Tree}
        :type c2: L{Tree}
        """
        self.child1 = c1
        self.child2 = c2

Show typeclass

class Person(object):
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

print repr(Person("John", "Doe"))
<__main__.Person instance at 0x7fa7910983f8>

Show typeclass

data Person = Person Name Surname

type Name    = String
type Surname = String

main = print (Person "John" "Doe")
a.hs:8:8:
    No instance for (Show Person) arising from a use of ‘print’
    In the expression: print (Person "John" "Doe")
    In an equation for ‘main’: main = print (Person "John" "Doe")

Show typeclass

class Person(object):
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

    def __repr__(self):
        return "<{0} {1} {2}>".format(
          self.__class__
        , repr(self.name)
        , repr(self.surname)
        )

print repr(Person("John", "Doe"))
<__main__.Person 'John' 'Doe'>

Show typeclass

data Person = Person Name Surname

type Name    = String
type Surname = String

instance Show Person where
    show (Person n s) = "Person \"" ++ n ++ "\" \"" ++ s ++ "\""

main = print (Person "John" "Doe")
Person "John" "Doe"

Show typeclass derivation

data Person = Person Name Surname
    deriving (Show)

type Name    = String
type Surname = String

main = print (Person "John" "Doe")
Person "John" "Doe"

Show & Read -> Guaranteed laws

data Person = Person Name Surname
    deriving (Show, Read)

type Name    = String
type Surname = String
x == read (show x)

Thank you

/

#