Home > Software engineering >  Build a list with length N
Build a list with length N

Time:11-08

I am trying to make a function that builds a list based on length n, some initial value, and builds the rest of the list applying some function/operation to the previous value . For example:

n = 5, initial_value = x, -> [x, fx, ... ]

I understand that to make a list of size n you can simply use replicate to give you a list, but perhaps it is not the best way to achieve this.

Code:

buildList::Int -> (b -> b) -> b -> [b]
buildList len func initial = replicate len something here 

Not sure what would come after "len".

CodePudding user response:

replicate will repeat the same value a number of times. That makes not much sense since we start with x, f x, f (f x), etc.

We can make use of iterate :: (a -> a) -> a -> [a] that will for iterate f x construct an infinite list [x, f x, f (f x), f (f (f x))), …].

We then should limit the list to the first N items. I leave it as an exercise to do this. The function thus looks like:

buildList :: Int -> (a -> a) -> a -> [a]
buildList len func initial = … (iterate func initial)

where you still need to implement the part.

  • Related