Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 605
northlane Avatar asked Aug 12 '17 14:08

northlane


People also ask

What is replicate Haskell?

replicate takes an Int and a value, and returns a list that has several repetitions of the same element.

Are there loops in Haskell?

Recursion is important to Haskell because unlike imperative languages, you do computations in Haskell by declaring what something is instead of declaring how you get it. That's why there are no while loops or for loops in Haskell and instead we many times have to use recursion to declare what something is.

What is twice in Haskell?

Twice instead is an example of self-composition (function iteration), which you can express through f . f . But note that there are no overloaded functions in Haskell - Every function in one scope has exactly one type and implementation (though this type may be polymorphic).


1 Answers

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,...]

like image 62
Willem Van Onsem Avatar answered Sep 25 '22 12:09

Willem Van Onsem