Loops/Foreach: Difference between revisions
→{{header|jq}}: iterables and strings
(→{{header|jq}}: range and keys) |
(→{{header|jq}}: iterables and strings) |
||
Line 954:
The Julia <code>for</code> statement is always a "foreach", and the built-in <code>start:end</code> or <code>start:step:end</code> "range" syntax can be used for iteration over arithmetic sequences. Many Julia objects support iteration: arrays and tuples iterate over each item, strings iterate over each character, dictionaries iterate over (key,value) pairs, numeric scalars provide a length-1 iteration over their value, and so on.
=={{header|jq}}==
'''Iterables''':
In this section, the array defined by "example" is used as an example:
<lang jq>def example: [1,2
jq has two types of iterables -- JSON arrays and JSON objects. In both cases, the ".[]" filter may be used to iterate through the values, it being understand that for objects, the "values" are the values associated with the keys:
<lang jq>example | .[]
# or equivalently: example[]</lang>
<lang jq>{"a":1, "b":2} | .[]
In both cases, the output is the stream consisting of the values 1 followed by 2.
Sometimes it is necessary to use an alternative to ".[]". For example, one might want to generate an index along with the array elements. In such cases, the "range(m;n)" generator, which performs a similar role to C's "for(i=m; i<n; i++)", can be used for array. Here is how range/2 would be used to perform the task for an array:
<lang jq>range(0; example|length) | example[.]</lang>
<lang jq>
{"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )▼
</lang>
produces:▼
[["a",1],["b",2]]▼
▲For JSON objects, the corresponding method involves using <tt>keys</tt>, e.g.
'''Strings''':
▲ {"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )
To convert the constituent characters (or technically, codepoints) of a string into a stream of values, there are two techniques illustrated by these examples:
▲produces:
<lang jq>"abc" | . as $s | range(0;length) | $s[.:.+1]
"abc" | explode | map( [.]|implode) | .[]</lang>
▲ [["a",1],["b",2]]
In both cases, the result is the stream of values: "a", "b", "c".
=={{header|Lasso}}==
|