romeoagogo
Limp Gawd
- Joined
- Aug 25, 2004
- Messages
- 159
Okay I am half-way through this scheme course and everything has been pretty easy thus far, but I am pretty stuck on this abstraction for reducing an arbitrary list of trees.
The assignment asks for me to take the following reduction function for a single tree and change it to handle N number of trees:
So I know I have to use the variable arity lambda to get an arbitrary number if trees into a list and I also know I have to make use of 'apply', but I am not sure if I'm using it completely correctly. Here is what I came up with:
This seems to me like it should work, but when testing this with the following function:
On the input: (tree-sumN '(1 (2) 3))
I get the error: 'Error in apply: 3 is not a proper list.'
Now I understand why the error is popping up, I just don't know what to do about it. The last argument of apply must be a proper list, but besides cons-ing an empty list to each recursive call (which I dont think works either) I don't know how to avoid this case. Any tips here would be really appreciated.
Thanks
The assignment asks for me to take the following reduction function for a single tree and change it to handle N number of trees:
Code:
(define tree-reduce
(lambda (f op id t)
(if (null? t)
id
(if (pair? t)
(op (tree-reduce f op id (car t))
(tree-reduce f op id (cdr t)))
(f t)))))
So I know I have to use the variable arity lambda to get an arbitrary number if trees into a list and I also know I have to make use of 'apply', but I am not sure if I'm using it completely correctly. Here is what I came up with:
Code:
(define tree-reduceN
(lambda (f op id . t)
(if (null? t)
id
(if (pair? t)
(op (apply tree-reduceN f op id (car t))
(apply tree-reduceN f op id (cdr t)))
(apply f t)))))
This seems to me like it should work, but when testing this with the following function:
Code:
(define tree-sumN
(lambda t
(apply tree-reduceN + + 0 t)))
On the input: (tree-sumN '(1 (2) 3))
I get the error: 'Error in apply: 3 is not a proper list.'
Now I understand why the error is popping up, I just don't know what to do about it. The last argument of apply must be a proper list, but besides cons-ing an empty list to each recursive call (which I dont think works either) I don't know how to avoid this case. Any tips here would be really appreciated.
Thanks