3

Learned to code C, long ago; wanted to try something new and different with Scheme. I am trying to make a procedure that accepts two arguments and returns the greater of the two, e.g.

(define (larger x y)
  (if (> x y)
    x
    (y)))

(larger 1 2)

or,

(define larger
  (lambda (x y)
    (if (> x y)
      x (y))))

(larger 1 2)

I believe both of these are equivalent i.e. if x > y, return x; else, return y.

When I try either of these, I get errors e.g. 2 is not a function or error: cannot call: 2

I've spent a few hours reading over SICP and TSPL, but nothing is jumping out (perhaps I need to use a "list" and reference the two elements via car and cdr?)

Any help appreciated. If I am mis-posting, missed a previous answer to the same question, or am otherwise inappropriate, my apologies.

h34thf
  • 33
  • 1
  • 4

1 Answers1

1

The reason is that, differently from C and many other languages, in Scheme and all Lisp languages parentheses are an important part of the syntax.

For instance they are used for function call: (f a b c) means apply (call) function f to arguments a, b, and c, while (f) means apply (call) function f (without arguments).

So in your code (y) means apply the number 2 (the current value of y), but 2 is not a function, but a number (as in the error message).

Simply change the code to:

(define (larger x y)
  (if (> x y)
      x
      y))

(larger 1 2)
Renzo
  • 26,848
  • 5
  • 49
  • 61
  • Brilliant! Thank you! I verified that this worked. I could see that the 2 is being treated like a function, but I could not understand why/how. Definite bias coming from C. Thanks, again. :-) – h34thf Feb 16 '17 at 16:10