Complex Data Objects

Using "data" to Create an Object

file: data.hs
1 data Foo = FooI Integer | FooD Float | FooS String
2     deriving Show
3 
4 main = putStrLn(show(FooI 3))
> ghc --make data.hs; ./data
[1 of 1] Compiling Main             ( data.hs, data.o )
Linking data ...
FooI 3

The names "FooI", "FooD", and "FooS" are called constructors. Since Haskell is functional, objects just stay the same after they are constructed.

Note the use of capital letters. Type names must always capitalized in Haskell.

The qualifier, "deriving Show", means that the object is a member of class "Show" and that Haskell can provide a default method for rendering the object as a string.


Getting the Data out of the Object

One way to get the data out of an object is to define a method that can do it.

file: udata.hs
1 data Foo = FooI Integer | FooD Float | FooS String
2     deriving Show
3 
4 p1 (FooI a) = FooI (a+1)
5 p1 (FooD a) = FooD (a+1.0)
6 p1 (FooS a) = FooS (a++"+1")
7 
8 main = do
9     putStrLn(show(p1(FooI 3)))
10     putStrLn(show(p1(FooD 3.0)))
11     putStrLn(show(p1(FooS "2")))
> ghc --make udata.hs; ./udata
[1 of 1] Compiling Main             ( udata.hs, udata.o )
Linking udata ...
FooI 4
FooD 4.0
FooS "2+1"

Building a Tree

file: tree.hs
1 data Tree a = NodeData a | Node (Tree a) (Tree a)
2     deriving Show
3 
4 tree = let
5     a = NodeData 1
6     b = NodeData 2
7     c = Node a b
8     d = NodeData 3
9     e = NodeData 4
10     f = Node d e
11     g = Node c f
12   in
13     g
14 
15 main = putStrLn(show(tree))
> ghc --make tree.hs; ./tree
[1 of 1] Compiling Main             ( tree.hs, tree.o )
Linking tree ...
Node (Node (NodeData 1) (NodeData 2)) (Node (NodeData 3) (NodeData 4))

Building a Doubly Linked List

file: dlink.hs
1 data DList = Null | DLink DList String DList
2 
3 list = let
4     a = DLink Null "first" b
5     b = DLink a "second" c
6     c = DLink b "third" d
7     d = DLink c "fourth" Null
8  in
9     b
10 
11 pra Null = putStrLn ""
12 pra (DLink Null b c) = pr (DLink Null b c)
13 pra (DLink a b c) = pra a
14 
15 pr Null = putStrLn ""
16 pr (DLink a b c) = do
17     case a of
18         Null -> putStr ""
19         otherwise -> putStr "<->"
20     putStr("DLink("++b++")")
21     pr c
22 
23 main = do
24     pr(list)
25     pra(list)
> ghc --make dlink.hs; ./dlink
[1 of 1] Compiling Main             ( dlink.hs, dlink.o )
Linking dlink ...
<->DLink(second)<->DLink(third)<->DLink(fourth)
DLink(first)<->DLink(second)<->DLink(third)<->DLink(fourth)