1
votes

I'm a beginner in Haskell and I'm trying to make a simple program that takes a list e.g [-3,8] and makes the infinite list: [-3,8,-3,8,-3,8,...]

Thanks to Haskell's lazy evaluation I've written a very simple program that computes it:

period :: [a]->[a]
period p = p ++ period p

I would like to know if exists a more simple solution using high order functions (iterate, map,...)

1
Consider using hoogle the next time. It's a search engine for Haskell. You can search by name or by type (see the linked search and how the first result is exactly cycle).Bakuriu

1 Answers

9
votes

The first place to look for list functions in general is Data.List. There you will find

cycle :: [a] -> [a]

which does exactly what you want. However, it is defined a little differently, so as to make a circular linked list instead of an infinite one. Something like

cycle xs = ys where ys = xs ++ ys

This can avoid a lot of unnecessary memory allocation. You can express this definition using Data.Function.fix:

cycle xs = fix (xs ++)

If you love to over-generalize, you can define this for general Semigroups using

cycle xs = fix (xs <>)

though this will diverge for most semigroups.

If you're a point-free fanatic, you can translate this to

cycle xs = fix ((<>) xs)

which you can then see is

cycle = fix . (<>)