简体   繁体   中英

How do you create and use datatypes in Haskell?

I am an Absolute Newbie to Haskell. But I really like it. I have been reading Learn You A Haskell and Real World Haskell and practicing along. I am on the Functionally Solving Problems section in the Learn You A Haskell book and I need someone to explain the following to me:

     data Node = Node Road Road | EndNode Road  
     data Road = Road Int Node 

Questions:

  • Is this some recursive data type creation?
  • Why Can't I do: Node "A" "B" and get a valid Node type? When I try something I can an error saying that Haskell can't match [Char] with Expected Road and I understand that. But I can't create a Node XY without a Road Int Node . I thought Road was a type synonym for String but since it isn't declared it certainly is not. If anyone read the book and understood this thing PLEASE EXPLAIN WHAT THOSE DATA TYPES MEAN AND PROVIDE EXAMPLE IF POSSIBLE.

Edit: The Chapter In Question >> Heathrow to London problem

Yes, these are mutually recursive data types.

To create values of these types you are likely to use recursion too. For example, here's a minimal road system - two nodes where each one lets you drive to the other:

nodeA, nodeB :: Node
nodeA = EndNode (Road 99 nodeB)
nodeB = EndNode (Road 99 nodeA)

Note how the definition of nodeA refers to nodeB and vice versa.

If I read the example in the book correctly it can be written like this:

aRoad, bRoad :: Road
aRoad = Road 50 a1
bRoad = Road 10 b1

a1, a2, a3, a4 :: Node
a1 = Node (Road 5 a2) (Road 30 b1)
a2 = Node (Road 40 a3) (Road 20 b2)
a3 = Node (Road 10 a4) (Road 25 b3)
a4 = EndNode (Road 0 b4)

b1, b2, b3, b4 :: Node
b1 = Node (Road 90 b2) (Road 30 a1)
b2 = Node (Road 2 b3) (Road 20 a2)
b3 = Node (Road 8 b4) (Road 25 a3)
b4 = EndNode (Road 0 a4)

Note again the mutual recursion of a1 and b1, a2 and b2 etc. for the crossing roads.

I've written the roads inline but of course you could name them all if you wanted:

roadA1ToB1 :: Road
roadA1ToB1 = Road 30 b1

If you did it this way the cycle of definitions would involve four of them - the definition of (the node) a1 would use roadA1ToB1 , which would use b1 , which would use roadB1ToA1 , which would use a1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM