Re: processing a sequence



André Thieme wrote:

joswig@xxxxxxxxxxxxxxxxxxxxxxx schrieb:

(defun collect-sublists (list)
(flet ((collect-sublist ()
(loop for element = (pop list)
while element collect element
while (and list
(<= element (first list))))))
(loop for sublist = (collect-sublist)
while sublist collect sublist)))

"We don't need no stinkin' loops!"

Ruby:

list = [0,1,2,3] * 3

def collect_sublists list, prev=nil, accum=[[]]
return accum if not element = list.first
if prev and element < prev
accum << [element]
else
accum[-1] << element
end
collect_sublists( list[1..-1], element, accum )
end

p collect_sublists( list )

# This could be slower if getting the last element in a list
# is expensive.

def collect_sublists_2 list, accum=[[]]
return accum if not element = list.first
if accum != [[]] and accum[-1][-1] > element
accum << [element]
else
accum[-1] << element
end
collect_sublists_2( list[1..-1], accum )
end


Nearly 15 minutes passed since you posted your solution, and William
James still didn?t show his Ruby one-liner that outperforms the Lisp
solution by a factor of 20 (speedwise). ;-)


André

Ruby is about the slowest "scripting language".
JavaScript is faster.

SpiderMonkey and jslibs:

LoadModule('jsstd')

list = [0,1,2,3,0,1,2,3,1,2,3]

function collect_groups( list, prev, accum )
{ accum = accum || [[]]
var element = list[0]
if ( typeof element == "undefined" )
return accum
if (prev && element < prev)
accum.push( [element] )
else
accum.slice(-1)[0].push( element )
return collect_groups( list.slice(1), element, accum )
}

Print( collect_groups(list).toSource(), '\n')

--- output ---
[[0, 1, 2, 3], [0, 1, 2, 3], [1, 2, 3]]
.



Relevant Pages

  • Re: Process notification
    ... As you see from prev. ... posts there is no obsolute user mode solution on how ... and then immidiatly terminated - your "monitoring loop" may not detect it. ... Vladimir ...
    (microsoft.public.win32.programmer.kernel)
  • RE: Extreme beginner question on reading lines from a file.
    ... print FILEOUT "M98PPECK.SUBL1\n"; ... the 1st line is written into $prev. ... This code will fail if there's ... If it fails it returns false and the loop exits. ...
    (perl.beginners)
  • copy error
    ... each time through loop ... It also returns a '1' which I dont not understand since it ... Shouldnt it be '0'? ... Prev by Date: ...
    (comp.lang.perl.misc)
  • Re: increasing counter whithin loop?
    ... Notching up the counter in a C-style loop is a _concise_ way to do ... prev = nil ... prev = elt ... I'm not sure I would find the C version clearer if I ...
    (comp.lang.ruby)
  • Re: Simplified LOOP
    ... which was a few years back) that the key problem with LOOP is ... the "collection problem". ... (define coll ($collect)) ... accum ) ...
    (comp.lang.lisp)