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:
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.