Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby: Manipulate Iterators?
    primarykey
    data
    text
    <p>I'm having teething problems with Ruby, with regards to creating single-direction, lazily-evaluated, potentially-infinite iterators. Basically, I'm trying to use Ruby like I'd use Haskell lists and, to a lesser extent, Python generators.</p> <p>It isn't that I don't understand them per se; I just don't know how to use them as casually as other languages, and I'm also unsure about what methods in Ruby will turn them into arrays behind my back, unloading the entire sequence into memory unnecessarily.</p> <p>And yes, I've been studying the Ruby reference manual. For half an hour in fact, attentively. Or perhaps evidently not.</p> <p>For example, if I were to implement a card deck, it would look something like this in Python (untested):</p> <pre><code># Python 3 from itertools import chain, count face_ranks = dict( zip( ('jack', 'queen', 'king', 'ace'), count(11))) sorted_deck = map( lambda suit: map( lambda rank: { 'rank' : rank, 'suit' : suit }, chain( range(2, 11), face_ranks.keys())), ('clubs', 'diamonds', 'hearts', 'spades')) </code></pre> <p>So, how would I do this in Ruby, completely avoiding arrays? Note that the above code uses, to my knowledge, only tuples and generators: at no point is the whole sequence dumped into memory like if I had used an array. I could be wrong about the above code, but you get what I want.</p> <p>How do I chain iterators (like Python's chain())? How do I generate an iterator of an infinite range (like Python's count())? How can I add an array to an iterator (like passing a tuple to Python's chain()) without converting the whole thing to an array in the process?</p> <p>I've seen solutions, but they involve arrays or unnecessary complexities like fibers.</p> <p>In Python I can manipulate and throw around iterators with the same simplicity as arrays. I can almost treat them like Haskell lists, which I'm most comfortable with, and is really what I think in when coding. I'm not comfortable with Ruby arrays, which is why I seek help with its alternative(s).</p> <p>I've managed to pick up nuggets of information on the internet about it, but I couldn't find any that covers basic manipulation of such data structures in Ruby? Any help?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload