gola
gola

Reputation: 9

Syntax for if-then-else in Racket

I have a problem with Racket.

(I'm using the tutorial at http://docs.racket-lang.org/guide/conditionals.html)

I tried to write a function that does this: If x is smaller than 4, then it should be incremented by 1, else it should be multiplied by 2.

(define (number x)
  (if (< x 4) 'x+1 'x*2))

So I compiled it on DrRacket, but it does nothing. The (if (< x 5) 'x+1 'x*2)) -Part is marked black! I think the Problem is the ' thing.

Upvotes: 0

Views: 1305

Answers (1)

amon
amon

Reputation: 57650

In Lisps, the ' is a shorthand for the quote operator, which prevents an S-Expression or symbol from being evaluated. While x would normally be a variable, quoting it turns it into a kind of lightweight string. Quotes are not part of the if syntax. It makes no sense to use quoting in your case.

Furthermore, Lisps do not use infix operators. Addition is just an ordinary function and everything, including addition, is written as an S-Expression. So instead of x + 1 we would write (+ x 1).

So our function would then look like:

(define (number x)
  (if (< x 4)
      (+ x 1)
      (* x 2)))

Upvotes: 8

Related Questions