سؤال

This shouldn't be this hard, but I'm stuck. We have a simple assignment where we're writing how to take the derivative of a function.

(define (derive exp var)
(cond ((number? exp) 0)
    ((variable? exp) (if (same-variable? exp var) 1 0))
    ((sum? exp) (derive-sum exp var))
    ((product? exp) (derive-product exp var))
    ((exponentiation? exp) (derive-exponentiation exp var))
    (else 'Error)))

But for the exponentiation, it needs to return true if I do have an exponential function. I'm just not entirely sure how to write it. So far I've just got something like this

(define (make-exponentiation base exponent)
   (cons base exponent)

(define (base exponentiation)
   (car exponentiation)

(define (exponent exponentiation)
   'cdr exponentiation)

(define (exponentiation? exp)
   'YourCodeHere)

(define (derive-exponentiation exp var)
   (* var (make-exponentiation exp (var-1)) (derive exp))

I'm not exactly sure what I'm checking about car and cdr. The whole thing is just a bit confusing. That's not the given code. I guess car and cdr are just kinda like placeholders at the moment.

هل كانت مفيدة؟

المحلول

It's quite some time, since I've done scheme. I'm more familiar with emacs lisp. So take with a grain of salt:

(define (make-exponentiation base exponent)
   (list '^ base exponent))

(define (base exponentiation)
   (car (cdr exponentiation)))

(define (exponent exponentiation)
   (car (cdr (cdr exponentiation))))

(define (exponentiation? exp)
   (equal? (car exp) '^))

(define (derive-exponentiation exp var)
   (let ((b (base exp))
         (e (exponent exp)))
   (make-product e (make-exponentiation b (- e 1))))

نصائح أخرى

Your code is pretty difficult to read because it is formatted oddly, you should try and seperate different things onto different lines. If you are using Dr. Racket you can also just hit tab and it will line everything up accordingly, but it will not fix having multiple things on the same line.

Anyways this problem depends a lot on how the assignment is set up and what sort of input you expect to take. You could use tags or you could just check to see if there is anything in the exponent spot, or if it is even just 0 or 1. Again though it depends entirely on how the input in being given.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top