0
votes

I have two questions about Haskell type expression:

Question 1 -

I would like to declare a type NODE

data NODE = Node String ATTR

and a type ATTR contains 3 sub-type as follow:

Source Bool

Target Bool

Ghost Int

data ATTR = Source Bool | Target Bool | Ghost Bool

But the above declaration does not satisfy the requirement that ATTR can contain whatever the combination of sub-types such as:

  • ATTR can contain Source Bool and Target Bool at once
  • ATTR can contain Source Bool, Target Bool and Ghost Int at once
  • ATTR can even be empty (contain nothing)

Question 2 -

I would like to declare a type GRAPH, in which a graph can contain 1 or many Statements (STMTS) or contain no Statement if the graph is empty. So I declare as follow:

data GRAPH = Graph String STMTS
data STMTS = STMT | STMTS

But again, as you see the recursive data type STMTS will repeat infinitively.

1
This sounds like homework, so here are some hints. Q1: consider the use of "Maybe". Q2: You need to consider this alternative definition of a list: data NonEmptyList a = Single a | Many a (NonEmptyList a). Don't worry about infinite data structures; Haskell eats them for breakfast.Paul Johnson

1 Answers

1
votes

For Question 1 I would say to use something like

data Attr = Attr (Maybe Bool) -- Source 
                 (Maybe Bool) -- Target 
                 (Maybe Bool) -- Ghost

For Question 2, I would use something like

data Graph = Graph [STMT]