I have built this function which calls a couple other functions to get the oprator and numbers for an arithmetic operation but I get the error function call: expected a function after the open parenthesis, but received '+. normaly you invoke addition as (+ 5 6) and multiplication as (* 4 9) ect. So I thought you could call a function that would get each piece but I cant seem to get it to work. Here is what I have:

(define calculate
  (lambda (x)
    ((getOperator x) (getOperand1 x) (getOperand2 x))
  )
)

Detailed explanations as to the reasons why what I'm doing is wrong are greatly apreciated.

Thanks

You can call a function that gets each piece, but your getOperator function needs to return +, not '+. For example this would work:

(define (get-operator expression)
  (cond
    ((some condition) +)
    ((other condition) *)
    (...)))

But this will not:

(define (get-operator expression)
  (cond
    ((some condition) '+)
    ((other condition) '*)
    (...)))

PS: The naming convention in Scheme (and Lisps in general) is to separate words in a name by -, not camel case. So getOperator would more idiomatically written as get-operator.

Thanks for the reply. I'm pulling apart a list to get the operator and operands using car and cdr how would I go about converting '+ into just +?

Ideally you'd make it so that the list contains + instead of '+ in the first place. If that's not possible (because you have no control over the lists), you could either use eval or a map or associative list that maps the symbols to their corresponding functions depending on your exact needs.

This is the test case thats giving me trouble(calculate '(2 + 3)) i dont see how im getting a '+ out of that when I call (cdr (car x))on it.
Thanks.

Because '(foo bar baz) is the same as (list 'foo 'bar 'baz) and since numeric constants are self-evaluating, '2 and '3 are just equal to 2 and 3, so the whole thing comes out as (list 2 '+ 3) (i.e. a list containing the number 2, the symbol + and the number 3).

So if that's your input, you'll need one of those options that I mentioned - or just a boring list of conditions like (equal? op '+), (equal? op '-) etc.

Ok that makes sense thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.