I have to define a list in which:
- 1 is a member
- if n is a member, so are 2n+1 and 3n+1
So the list is infinite and must be sorted. When loaded to GHCi, the command:
"take 10 theList"
will produce:
[1,3,4,7,9,10,13,15,19,21]
Below are my codes:
theList = ([1] ++ concat [[(x*2+1),(x*3+1)]|x<-theList])
It seems to work except for that it is not sorted, the same command as above produces:
[1,3,4,7,10,9,13,15,22,21]
Does anyone have any idea to sort that out?
Thanks
The problem can be though of as a infinite binary tree (
AandBare labels for the branches):Thinking about it this way, we can see that we want to write a function (“
listify“) that converts the “tree” into a sorted list. This is where Haskell is really nice: if we have a function (merge) that takes two (infinite) sorted lists and merges them into one sorted list (you should write this function), thenlistify-ing the tree is simplylistify-ing the two branches, merging them and putting the root at the start, i.e. in the tree aboveSince this is homework I won’t say much more, but any branch of the tree is entirely determined by the root node, so the type signature of
listifycan beInteger -> [Integer]. And once you havelistify, thentheList = listify 1.