[parenscript-devel] Loops that return a value

Daniel Gackle danielgackle at gmail.com
Tue Jan 15 20:55:12 UTC 2013


> What about looping over arrays and objects?

Here are some examples for you. PS's LOOP mostly, but not entirely,
agrees with CL's LOOP. So for example you can not only :COLLECT
things, as Boris illustrated, but :APPEND them if they happen to be
lists (arrays, of course, in JS):

  (loop :for arr :in '((10 20) (30 40)) :append (reverse arr))
  => (20 10 40 30)

You can do numeric things like SUM, COUNT, MINIMIZE, and MAXIMIZE:

  (loop :for i :in '(10 20 30 40) :sum i)
  => 100

You can bind to destructuring lists rather than symbols, using
the same notation as BIND:

  (loop :for (a (nil b)) :in '((10 (20 30)) (100 (200 300)))
     :collect (list a b))
  => ((10 30) (100 300))

  (loop :for ((:a) (:b)) :in (list (list (create a 10 b 20) (create a 55 b
88))
                                   (list (create a 100 b 200) (create a 555
b 888)))
        :collect (list a b))
  => ((10 88) (100 888))

Those examples use contrived literals, but the notation is very useful
when iterating over object/array collections.

In addition, PS's LOOP has :MAP..TO and :OF, which are designed for
working with JS objects. These are not derived from CL. CL LOOP's
provisions for iterating over hash tables are cumbersome and not quite
a good fit for JS, so we introduced these.

To iterate over the keys of an object:

  (loop :for k :of (create :a 1 :b 2) :collect k)
  => ("a" "b")

To iterate over the key-value pairs:

  (loop :for (k v) :of (create :a 1 :b 2) :collect (list k v))
  => (("a" 1) ("b" 2))

To iterate over just the values:

  (loop :for (nil v) :of (create :a 1 :b 2) :sum v)
  => 3

To destructure the values:

  (loop :for (id (:name)) :of (create 123 (make :name "joe" :num 9)
                                      345 (make :name "ann" :num 10))
          :collect (list id name))
  => (("123" "joe") ("345" "ann"))

To build a new object, use :MAP key :TO value:

  (loop :for str :in '("abc" "xy" "defg") :map str :to (length str))
  => { abc 3 defg 4 xy 2 }

It would be great to have a tutorial showing what amazing things you
can do when you compose the different pieces of LOOP together. But in
the meantime I hope this helps. Please post any other questions you
have, and if you find any bugs, definitely post those.

Daniel

On Tue, Jan 15, 2013 at 1:05 PM, David Sargeant <david at dsargeant.com> wrote:

> Thanks for sharing that.  What about looping over arrays and objects?
>
>
> David
>
> _______________________________________________
> parenscript-devel mailing list
> parenscript-devel at common-lisp.net
> http://lists.common-lisp.net/cgi-bin/mailman/listinfo/parenscript-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/parenscript-devel/attachments/20130115/68e45d42/attachment.html>


More information about the parenscript-devel mailing list