dolist but getting more values at the same time

Started by ale870, March 28, 2010, 03:30:36 PM

Previous topic - Next topic

TedWalther

#15
Here is my solution:



(setq lst '(a b c d e f g 1 2 3 4 5))
(dotimes (i (- (length lst) 2))
  (do-something (i 3 lst)))


The code gives you your moving window.  It also lets you access the original list, in case your code needs to modify the original list.  And it doesn't make duplicates of the original list, so should be more efficient.
Cavemen in bearskins invaded the ivory towers of Artificial Intelligence.  Nine months later, they left with a baby named newLISP.  The women of the ivory towers wept and wailed.  \"Abomination!\" they cried.

Lutz

#16
This is how you could build generators for different window sizes and shifts. The generator sees the list as a circle and can go around if required.




(define (make-window-generator size shift thelist)
   (expand (fn () (0 size (rotate 'thelist shift))) 'size 'shift 'thelist))

; or alternative syntax of expand uppercasing the vars to expand

(define (make-window-generator Size Shift Thelist)
   (expand (fn () (0 Size (rotate 'Thelist Shift)))))

(define gen (make-window-generator 3 -1 (sequence 0 9)))

(gen) => (1 2 3)
(gen) => (2 3 4)
(gen) => (3 4 5)

shift is negative for rotating left, positive for rotating right.

rickyboy

#17
Quote from: "TedWalther"And it doesn't make duplicates of the original list, so should be more efficient.

This concern is not practically an issue with the function generate-moving-window.  According to the manual at the section entitled http://www.newlisp.org/downloads/newlisp_manual.html#pass_big">Passing Data By Reference -- and this also bears out with a little testing -- if the list you pass your function is not large, "the speed difference between reference and value passing is negligible"; if your list is large enough to notice the copy, the manual recommends to pass that list by reference: "Strings and lists, which are packed in a namespace using default functors, are passed automatically by reference."



While I prefer that method, another way to avoid copying a big list in calling generate-moving-window is to change its definition from a lambda to a lambda-macro (and an accompanying letex, of course).


Quote from: "TedWalther"It also lets you access the original list, in case your code needs to modify the original list.

Well, I don't know what to say to this, except: "Knock yourself out, brother!"  :)  I'm a functional programmer; so my whole outlook on programming is based on NOT doing that.  ;)
(λx. x x) (λx. x x)

William James

#18
I enjoy using the int-reduce option in apply.

When int-reduce is 2, the behavior is like fold or reduce; when it's larger than 2, it's even more fun.



> (apply (fn(_ a b c)(println a b c)) (cons nil (sequence 1 9)) 4)
123
456
789