Loop that collects results?

Started by kinghajj, July 18, 2007, 10:14:39 AM

Previous topic - Next topic

kinghajj

Is there a loop that returns a list of the results of each iteration? For example:



(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.

cormullion

#1
(map (fn (n) (* n 2)) (sequence 1 10))
;-> (2 4 6 8 10 12 14 16 18 20)


map will collect it for you.

Jeff

#2
(map (curry * 2) '(1 2 3...))
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

cormullion

#3
(map << (sequence 1 10))

;-)

Jeff

#4
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]
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code

jrh

#5
Quote from: "Jeff"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!



---

jrh

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

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

---

cormullion

#7
that's so silly, i love it!

jrh

#8
Don't let that computer just sit there.  Generate some cpu cycles!


> (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)

---

Jeff

#9
double_elements.so:
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
(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))
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code