northlane
northlane

Reputation: 293

How to repeat a list of functions in haskell

I want to have an infinite list of functions that cycles through some pattern. For example: [(+), (-), (+), (-), ...]

If I do something like

fmap repeat [(+), (-)]

then I get nested lists [[a -> a -> a]]. What's the best way to get a single infinite list of functions following a pattern like this?

Upvotes: 5

Views: 416

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

What you are looking for is cycle :: [a] -> [a]:

cycle [(+),(-)]

The type of this expression is:

Prelude> :t cycle [(+),(-)]
cycle [(+),(-)] :: Num a => [a -> a -> a]

cycle takes a list [a] and produces a list where the given list is repeated over and over again. So cycle [1,2,3] produces [1,2,3,1,2,3,1,2,3,1,...]

Upvotes: 13

Related Questions