Iterators: Difference between revisions

Content added Content deleted
(J)
Line 82: Line 82:
</pre>
</pre>



=={{header|J}}==

J's operations are designed to be applied to the data structure as a whole, and this explicitly includes mapping between representations. Also, all data in J is array-like, and type is data. And this necessarily includes linked lists (though we can introduce arbitrarily complex mechanisms to obfuscate a linked list structure).

Still, one approach here might be:

<lang J>dow=: ;:'monday tuesday wednesday thursday friday saturday sunday'
col=: (,<)/;:'red orange yellow green blue purple'</lang>

This gives us:

<lang J>
dow
┌──────┬───────┬─────────┬────────┬──────┬────────┬──────┐
│monday│tuesday│wednesday│thursday│friday│saturday│sunday│
└──────┴───────┴─────────┴────────┴──────┴────────┴──────┘
col
┌───┬─────────────────────────────────────────┐
│red│┌──────┬────────────────────────────────┐│
│ ││orange│┌──────┬───────────────────────┐││
│ ││ ││yellow│┌─────┬───────────────┐│││
│ ││ ││ ││green│┌────┬────────┐││││
│ ││ ││ ││ ││blue│┌──────┐│││││
│ ││ ││ ││ ││ ││purple││││││
│ ││ ││ ││ ││ │└──────┘│││││
│ ││ ││ ││ │└────┴────────┘││││
│ ││ ││ │└─────┴───────────────┘│││
│ ││ │└──────┴───────────────────────┘││
│ │└──────┴────────────────────────────────┘│
└───┴─────────────────────────────────────────┘</lang>

Here, language's array indexing would see the linked list representation as a two element array. To index arbitrary elements from the linked list, we might map back from the linked list representation to a flat array representation, perhaps using <S:0 (which is a no-op on our array of days of week).

<lang J> echo ;:inv <S:0 dow
monday tuesday wednesday thursday friday saturday sunday
echo ;:inv <S:0 col
red orange yellow green blue purple

echo ;:inv 0 3 4 {<S:0 dow
monday thursday friday
echo ;:inv 0 3 4 {<S:0 col
red green blue

echo ;:inv _1 _3 _4 {<S:0 dow
sunday friday thursday
echo ;:inv _1 _3 _4 {<S:0 col
purple green yellow</lang>

The downside of this approach is that the programmer must understand the data.

However, given the intrinsic value of comprehension when programming, this is frequently a worthwhile price.


=={{header|Julia}}==
=={{header|Julia}}==