Page 1 of 1

Loop that collects results?

Posted: Wed Jul 18, 2007 5:14 pm
by kinghajj
Is there a loop that returns a list of the results of each iteration? For example:

Code: Select all

(collect (n (sequence 1 10))
    (* n 2))
; => (2 4 6 8 10 12 14 16 18 20)
I'm sure there are other ways to do this, like using map and curry. I could probably implement this as a macro, if there is no current way to do this.

Posted: Wed Jul 18, 2007 6:06 pm
by cormullion

Code: Select all

(map (fn (n) (* n 2)) (sequence 1 10))
;-> (2 4 6 8 10 12 14 16 18 20)
map will collect it for you.

Posted: Wed Jul 18, 2007 8:18 pm
by Jeff
(map (curry * 2) '(1 2 3...))

Posted: Wed Jul 18, 2007 8:44 pm
by cormullion

Code: Select all

(map << (sequence 1 10))
;-)

Posted: Wed Jul 18, 2007 11:50 pm
by Jeff

Code: Select all

int main
{
    int seq[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int result[10];
    int i;
    for (i = 0; i < 10; i++)
    {
        result[i] = seq[i] * 2;
    }
    return 0;
}
[/code]

Posted: Thu Jul 19, 2007 9:14 am
by jrh
Jeff wrote:

Code: Select all

int main
{
    int seq[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int result[10];
    int i;
    for (i = 0; i < 10; i++)
    {
        result[i] = seq[i] * 2;
    }
    return 0;
}
I think I see what you mean!

---

Re: Loop that collects results?

Posted: Thu Jul 19, 2007 9:20 am
by jrh

Code: Select all

> (rest (filter (lambda (x) (= (% x 2)0)) (sort (unique (rand 21 210)))))

(2 4 6 8 10 12 14 16 18 20)
---

Posted: Fri Jul 20, 2007 8:10 am
by cormullion
that's so silly, i love it!

Posted: Fri Jul 20, 2007 11:40 pm
by jrh
Don't let that computer just sit there. Generate some cpu cycles!

Code: Select all

> (map eval (transpose (append (transpose (dup (list (sym (char 42)) 2) 10)) (list (rest (index string? (explode "C++  sucks!")))))))

(2 4 6 8 10 12 14 16 18 20)
---

Posted: Sat Jul 21, 2007 2:24 am
by Jeff
double_elements.so:

Code: Select all

void double_list_elements(int seq[], int seq_length, int result[])
{
    int i;
    for (i = 0; i < seq_length; i++)
    {
        result[i] = seq[i] * 2;
    }

}
my_script.lsp

Code: Select all

(import "double_elements.so "double_list_elements")
(set 'seq (sequence 1 10))
(set 'set2 '(array 10 (sequence 1 10))
(double_list_elements seq (length seq) seq2))