Haskell, define an endless list, add data on the fly and sort at the same time. How?

I need to define a list in which:

  • 1 is a member
  • if n is a member, so 2n + 1 and 3n + 1

So the list is endless and needs to be sorted. When loading into GHCi 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 that it doesn't sort, the same command as above creates:

[1,3,4,7,10,9,13,15,22,21]

Does anyone have an idea to figure this out? Thanks

+5
source share
2 answers

The problem can be like an infinite binary tree ( Aand Bthese are labels for the branches):

  1__ B
  |  4___
  |   \  13 ...
A 3_   \
  | \   9 ...
  7  10
  ...

, , ( "listify" ), "" . Haskell : (merge), () ( ), listify - listify - , , ..

1:merge (listify A) (listify B)

, , node, listify Integer -> [Integer]. listify, theList = listify 1.

+7

. n , n = 1 (mod 2) (n-1)/2 , n = 1 (mod 3) (n-1)/3 .

+4

All Articles