Stream merge: Difference between revisions

Line 1,522:
 
say merge_streams([ @*ARGS».&open ]);</lang>
 
=={{header|Phix}}==
Using a priority queue
<lang Phix>include builtins/pqueue.e -- (0.8.0+, not yet properly documented)
 
procedure add(integer fn, pq)
object line = gets(fn)
if line=-1 then
close(fn)
else
pq_add({fn,line}, pq)
end if
end procedure
 
-- setup (optional/remove if files already exist)
constant data = {"Line 001\nLine 008\nLine 017\n",
"Line 019\nLine 033\nLine 044\nLine 055\n",
"Line 019\nLine 029\nLine 039\n",
"Line 023\nLine 030\n"},
filenames = {"file1.txt","file2.txt","file3.txt","file4.txt"}
-- (or command_line()[3..$] if you prefer)
 
for i=1 to length(filenames) do
integer fn = open(filenames[i], "w")
if fn<0 then crash("cannot open file") end if
puts(fn, data[i])
close(fn)
end for
 
-- initilisation
integer pq = pq_new()
for i=1 to length(filenames) do
integer fn = open(filenames[i], "r")
if fn<0 then crash("cannot open file") end if
add(fn,pq)
end for
 
-- main loop
while not pq_empty(pq) do
{integer fn, string line} = pq_pop(pq)
puts(1,line)
add(fn, pq)
end while
pq_destroy(pq)
 
-- cleanup (optional/remove if files already exist)
for i=1 to length(filenames) do
{} = delete_file(filenames[i])
end for</lang>
{{out}}
<pre>
Line 001
Line 008
Line 017
Line 019
Line 019
Line 023
Line 029
Line 030
Line 033
Line 039
Line 044
Line 055
</pre>
 
=={{header|PicoLisp}}==
7,813

edits