List comprehensions: Difference between revisions

(Added Kotlin)
Line 1,463:
 
Note that <tt>gather</tt>/<tt>take</tt> is the primitive in Perl&nbsp;6 corresponding to generators or coroutines in other languages. It is not, however, tied to function call syntax in Perl&nbsp;6. We can get away with that because lists are lazy, and the demand for more of the list is implicit; it does not need to be driven by function calls.
 
=={{header|Phix}}==
Phix does not have builtin support for list comprehensions.
 
However, consider the fact that the compiler essentially converts an expression such as s[1] into calls
to the low-level back end (machine code) routines :%opRepe and :%opSubse depending on context (although
somtimes it will inline things and sometimes it will use opRepe1/opRepe1ip/opRepe1is and
opSubse1/opSubse1i/opSubse1is/opSubse1ip variants for better performance).
 
Thinking laterally, Phix also does not have any special syntax for dictionaries, instead they are supported
via an autoinclude with the following standard hll routines:
<lang Phix>global function new_dict(integer pool_only=0)
global procedure destroy_dict(integer tid, integer justclear=0)
global procedure setd(object key, object data, integer tid=1)
global function getd(object key, integer tid=1)
global procedure destroy_dict(integer tid, integer justclear=0)
global function getd_index(object key, integer tid=1)
global function getd_by_index(integer node, integer tid=1)
global procedure deld(object key, integer tid=1)
global procedure traverse_dict(integer rid, object user_data=0, integer tid=1)
global function dict_size(integer tid=1)</lang>
Clearly it would be relatively trivial for the compiler, just like it does with s[i], to map some other new
dictionary syntax to calls to these routines (not that it would ever use the default tid of 1), although
admittedly traverse_dict might prove a bit trickier than the rest. Since Phix is open source, needs no other tools, and
compiles itself in 10s, that is not as unreasonable as it might first sound.
 
With all that in mind, the following might be a first step to list comprehension support:
<lang Phix>--
-- demo\rosetta\List_comprehensions.exw
-- ====================================
--
function list_comprehension(sequence s, integer rid, integer nargs, integer level=1, sequence args={})
sequence res = {}
args &= 0
for i=1 to length(s) do
args[$] = s[i]
if level<nargs then
res &= list_comprehension(s,rid,nargs,level+1,args)
else
res &= call_func(rid,args)
end if
end for
return res
end function
 
function triangle(integer a, b, c)
if a<b and a*a+b*b=c*c then
return {{a,b,c}}
end if
return {}
end function
 
?list_comprehension(tagset(20),routine_id("triangle"),3)</lang>
{{out}}
<pre>
{{3,4,5},{5,12,13},{6,8,10},{8,15,17},{9,12,15},{12,16,20}}
</pre>
 
=={{header|PicoLisp}}==
7,820

edits