Haskell: Using List Comprehension and reducing x by 1 each list to make x amount of lists

Viewed 693

I'm new to using Haskell I've been spending hours trying to build a simple function where entering a function will turn out like this:

makeList 5 == [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
makeList 2 == [[1],[1,2]]

No amount of research can really help me figure out how I should iterate my functions 'x' so that I have multiple lists building based on the number I choose, I'm close but that's where I'm stumped, my current code is essentially set up where I can do this if I were to enter makeList 3:

makeList 3 = [ [ x | x <- xs ] | xs <- [[1..x-2],[1..x-1],[1..x]] ]

prints out:

[[1],[1,2],[1,2,3]]
2 Answers
Prelude> makeList n = [ [1..x] | x <- [1..n] ]
Prelude> makeList 5
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]

Or you can use explicit recursion.

makeList :: Int -> [[Int]]
makeList cap = go 1 where
  go num | num < cap = [1..num]:go (num+1)
         | otherwise = [1..num]:[]
Related