Justin Raymond
Justin Raymond

Reputation: 3558

Haskell cycle a vector

Is there a vector alternative of Data.List's cycle?

The Data.Vector docs have a section titled Recycling support that sounds like it is what I would want but the functions new and clone clearly don't do what cycle does.

The solution I was thinking about is just repeatedly index the vector with (a counter mod the length of the vector).

An example of what I needed to do, is I need an infinite list of randomly shuffled grids, but the grids are large and so keeping millions of them in memory is not ideal. I realized that it did not matter if the cycle of random was relatively small, so instead I generated a list of only a couple hundred grids and then used Data.List.cycle to give the illusion of infinite length. I am now converted the list of grids to a Vector of grids and can no longer use cycle.

Upvotes: 4

Views: 280

Answers (2)

gallais
gallais

Reputation: 12093

If you want a finite representation of cyclic lists (not vectors so you'll still have an access time linear in the size of the cycle), you may want to have a look at this module I was playing with last year.

By the way, the reason why the type of fold is quite weird is explained here. Basically the idea is that we may or may not decide to unfold the cycle depending on whether we use the induction hypothesis given to us.

Upvotes: 2

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

No. The existing Vector's in the Vector package allocate at least the spine and thus you can not have Vector.cycle without infinite memory.

For example, Data.Vector uses Data.Primitive.Array.

Since the internals of the vector package (e.g. Data.Vector.Generic.*) allow you to define other types of Vectors in a flexible manner, you could make a vector type that computes the index modulo the length to provide cyclic behavior (and includes an offset for use with drop). So the construction is conceivable, just not done.

Upvotes: 9

Related Questions