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?
replicate takes an Int and a value, and returns a list that has several repetitions of the same element.
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.
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).
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,...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With