当前位置: 动力学知识库 > 问答 > 编程问答 >

scheme - 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.

网友答案:

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)))
分享给朋友:
您可能感兴趣的文章:
随机阅读: