Reputation: 53
I'm trying to solve this problem. I was wondering if someone would help get started on it or give me some hints.
function called apply-all
that, when given a list of functions and a number, will produce a list of the values of the functions when applied to the number.
For example,
(apply-all (list sqrt square cube) 4)
=> (2 16 64)
Thanks
OK. this is what I have so far,
(define (apply-all lst num)
(apply-allaux lst num '()))
;; aux function
(define (apply-allaux lst num acc)
(if (null? lst)
acc
(apply-allaux (cdr lst) num (cons (apply (car lst) num)))))
but when I run this
(apply-all '(positive?) 2)
it gives me this error
mcar: expects argument of type <mutable-pair>; given 2
Can anyone help me find the problem please?
Upvotes: 1
Views: 1853
Reputation: 325
Given the signature:
; apply-all : (listof (number -> number)), number -> (listof number)
Consider what apply-all should return:
Upvotes: 0
Reputation: 222973
In response to your attempt, I'll provide you some hints to get you through. :-)
apply
in your case. apply
doesn't do what you think it does, notwithstanding that your assignment wants you to make a function called apply-all
.cons
takes two arguments.'(positive?)
is a list that contains a symbol named positive?
, not the positive?
function. Your assignment used (list ...)
for good reason. If you want something more compact than list
, use quasiquotation: `(,positive?)
.map
, like Marcin's comment suggests.map
, then remember that when you use the "iterate with accumulator" pattern, your results come out reversed. You must either reverse the input list or the result.Here's my reference solution, which took me half a minute to write. :-) I'm hoping you can use it to fine-tune your existing version. (I'm comfortable with posting it because I'm certain your markers won't let you use cut
, and if you can work out how to make my version acceptable to your markers, then you've already won.)
(define (apply-all fns . args)
(map (cut apply <> args) fns))
Upvotes: 1
Reputation: 17203
Captain Pedantic says: have you taken a look at How To Design Programs (http://www.htdp.org) ?
You need to start by writing down examples--simpler ones than the one you have. Also, write the result in a form in which it actually evaluates correctly. (In your example, for instance, if you evaluate (2 16 64), you'll get an error.
Next, if you don't have experience developing functions over lists, you should really really be reading the first ten sections of HtDP; it's far better than a Stack Overflow answer can be.
Hope this helps!
Upvotes: 2