Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell cycle a vector

Tags:

haskell

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.

like image 428
Justin Raymond Avatar asked Dec 19 '22 01:12

Justin Raymond


2 Answers

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.

like image 158
Thomas M. DuBuisson Avatar answered Jan 14 '23 09:01

Thomas M. DuBuisson


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.

like image 37
gallais Avatar answered Jan 14 '23 10:01

gallais