1

My goal is to create an infinite list by applying a function to the last element. For example if I begin with a list that looks like

[1]

and apply the function f(x) = (x + 2) * 10, I should end with

[1, 30, 320, 3220, 32220...]

How would I code this in Haskell?

3 Answers 3

3

iterate:

Prelude> let f x = (x + 2) * 10 in take 5 $ iterate f 1
[1,30,320,3220,32220]
Sign up to request clarification or add additional context in comments.

Comments

2

There's iterate

iterate :: (a -> a) -> a -> [a] -- Repeat a function forever, making a list of values

If you want to start with a list and only operate on its last element:

func f xs = (init xs) ++ (iterate f $ last xs)

Comments

0

You've already got your answer: you use iterate. Here's how you can code it yourself.

iterate takes a function f and a seed x, and repeats function application forever (i.e. returns [x, f x, f (f x), f (f (f x)), ...])

iterate :: (a -> a) -> a -> [a]
iterate f x = x : map f (iterate f x)

4 Comments

How about iterate f (f x) instead of map f (iterate f x)?
@Ryan Yours is a better implementation, and indeed the one that GHC uses.
iterate f x = ys where ys = x : map f ys should be better.
@Ryan you are right, it is better implementation-wise, but putting it this way, or even Will's way it's more clear that there's a fix point going around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.