1

I would like to have two expressions evaluated in function body. How would I go about it?

Given the following:

(define (f)
  ((+ 2 2) (+ 4 4)))

I would like both to have 2+2 and 4 + 4 evaluated (obviously the above doesn't work).

Basically, if I understand it correctly, in a spot where I can get a single thing done, I would like to have two things done. For example instead of calling just one function as a consequent in the if expression, I'd like to call two functions. Or ideally return a value and have the function call itself.

I am not sure if this makes sense but conceptually having such a mechanism seems plausible.

4

3 回答 3

12

过程的主体从上到下计算,无论开头有多少表达式,都只返回最后一个的值。例如,如果我们这样写:

(define (f)
  (+ 2 2)  ; evaluates to 4, but we don't do anything with it, so it's lost
  (+ 4 4)) ; evaluates to 8, this is the returned value

...当我们调用(f)返回值 is8时,第一个表达式的值会丢失。也许您的意思是,您希望返回多个值?这可能取决于解释器,例如在 Racket 中:

(define (f)
  (values (+ 2 2) (+ 4 4)))

(f)
=> 4
   8

现在(f)返回两个值,如果我们要使用它们,我们需要特殊的形式来“捕获”多个返回值。在此示例中,我将使用let-values

(let-values (((x y) (f))) ; 4 is bound to x, 8 is bound to y
  (+ x y))
=> 12

关于使用if表达式的问题的另一种解释:如果您需要在 a 中编写多个表达式if,那么您必须将所有表达式打包在一个begin表单中(顺便说一下:过程的主体隐含在 a begin)。

但是再一次,即使所有表达式都是按顺序执行的,也只会返回最后一个的值作为结果——所以中间的所有表达式都应该只为效果而执行,而不是为值。例如:

(if (= 1 1)    ; condition is true
    (begin     ; execute a sequence of expressions
      (+ 2 2)  ; evaluates to 4, but the value is lost
      (+ 4 4)) ; evaluates to 8, this is the returned value
    (begin
      (+ 1 1)
      (+ 3 3)))
=> 8

当然,在上面的例子中,只使用 a 会更简单cond,它有一个隐含的begin。这相当于前面的代码片段:

(cond
  ((= 1 1)   ; condition is true, implicit `begin`
   (+ 2 2)   ; evaluates to 4, but the value is lost
   (+ 4 4))  ; evaluates to 8, this is the returned value
  (else
   (+ 1 1)
   (+ 3 3)))
=> 8
于 2013-09-25T13:57:23.417 回答
1

我不确定我理解你的意思,你只是一个接一个地调用函数:

(define (f)
  (display "calling-function-1")
  (newline)
  (display "calling-function-2"))

输出:

Welcome to DrRacket, version 5.3.5 [3m].
Language: SICP (PLaneT 1.17); memory limit: 128 MB.
> (f)
calling-function-1
calling-function-2

如果您通过添加执行此操作:

(define (f)
  (+ 2 2) (+ 4 4))

它仍然可以正常工作,并且只返回最后一个值:

Welcome to DrRacket, version 5.3.5 [3m].
Language: SICP (PLaneT 1.17); memory limit: 128 MB.
> (f)
8
于 2013-09-25T13:48:18.007 回答
1

如果你想在一个只允许一个表达式的地方计算一个表达式序列(即一个if结果),你需要使用begin. 对于 a 的主体,情况并非如此define

于 2013-09-25T14:02:28.400 回答