[racket] dotted-tail notation
The dotted notation will give you the rest of the args in a list but
you still have to call the function in the standard way. In your
recursive call, you are giving the function a list of arguments
instead of each argument individually. Here's the output if I print
items on each call to list-rf:
(1 4 9 16 25 1 4 9 16 25 1 4 9 16 25 1 4 9 16 25)
((4 9 16 25 1 4 9 16 25 1 4 9 16 25 1 4 9 16 25))
(())
(())
You can use apply to do what you want here:
(define list-rf (lambda ( n . items )
(if (= n 0)
(car items)
(apply list-rf (- n 1)(cdr items)))))
(list-rf 3 1 4 9 16 25 1 4 9 16 25 1 4 9 16 25 1 4 9 16 25)
=> 16
On Tue, Nov 20, 2012 at 12:45 PM, sam <throwit1 at hotmail.com> wrote:
> I already spent a couple of hours on this, hope I am not missing something really obvious - does the dotted notation produce some kind of flat list instead of cons cells?
>
>
>
> (define list-rf (lambda ( n . items )
> (if (= n 0)
> (car items)
> (list-rf (- n 1)(cdr items)))))
>
> (list-rf 3 1 4 9 16 25 1 4 9 16 25 1 4 9 16 25 1 4 9 16 25)
>
> output: '()
>
> If I try to end the recursion on (null? items) it goes into an infinite loop
>
>
> (define test2 (lambda y
> (if (or(null? y)(null? (cdr y)))
> y
> (printf"~a~n"(cons (car y) (test2 (cdr y)))))))
>
>
>
> (test2 1 2 3 4 5 6 7);=> <i>(1 3 5 7)</i>
> (trace test2)
>
> output:
> {2 {3 4 5 6 7}}
> {1 {2 3 4 5 6 7}}
>
> and test2 doesn't recur. If I replace that (if (or (null ...
> with
> (if (null? y)
>
> the prompt never returns.
>
> it's confusing the heck out of me.
> ____________________
> Racket Users list:
> http://lists.racket-lang.org/users