Search code examples
schememit-scheme

Scheme procedure with 2 arguments


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.


Solution

  • 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)