newLISP Fan Club

Forum => newLISP newS => Topic started by: kinghajj on July 18, 2007, 10:14:39 AM

Title: Loop that collects results?
Post by: kinghajj on July 18, 2007, 10:14:39 AM
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.
Title:
Post by: cormullion on July 18, 2007, 11:06:45 AM
(map (fn (n) (* n 2)) (sequence 1 10))
;-> (2 4 6 8 10 12 14 16 18 20)


map will collect it for you.
Title:
Post by: Jeff on July 18, 2007, 01:18:29 PM
(map (curry * 2) '(1 2 3...))
Title:
Post by: cormullion on July 18, 2007, 01:44:53 PM
(map << (sequence 1 10))

;-)
Title:
Post by: Jeff on July 18, 2007, 04:50:05 PM
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]
Title:
Post by: jrh on July 19, 2007, 02:14:14 AM
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!



---
Title: Re: Loop that collects results?
Post by: jrh on July 19, 2007, 02:20:41 AM
> (rest (filter (lambda (x) (= (% x 2)0)) (sort (unique (rand 21 210)))))

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

---
Title:
Post by: cormullion on July 20, 2007, 01:10:47 AM
that's so silly, i love it!
Title:
Post by: jrh on July 20, 2007, 04:40:36 PM
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)

---
Title:
Post by: Jeff on July 20, 2007, 07:24:05 PM
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))