Scheme storing the result of a function (Let)

怎甘沉沦 提交于 2019-12-11 05:05:11

问题


(define [DML vara] 
  (cond
     ((atom? (car vara)) 
      (cond
        ((eqan? (car vara) 'N)
         (display (cdr vara)))
        (else (negate vara)))

   )))

I'm currently trying to save the content of a return right now for simplicity I was testing the negate function it "returns" a list and I wanted to save the result of that function to do testing. How do I actually save the list return from negate. Kind of like (x = (negate vara)) where x is the list. I look up let on google and in stack over flow but I can't find a very simple basic assignment.

Excuse my poor syntax on scheme I'm just starting..and going from imperative language to function isn't so smooth..

edit:

I wanted to print out the result expression of (negate vara) but since scheme only prints out the last "recursive call" (pardon my bad wording). I wanted it to use the resulting list from (negate vara) but still print out that list like

say if I had 
(else (test (negate vara)))
...
(define (test vara)
(display "test")
)

I wanted it to display 
'(O a b)) ;list
here

回答1:


As you already know, a let expression will do the trick:

(let ((x 10)
      (y 20))
  (+ x y))

=> 30

The above expression binds values to two variables, x and y. These bindings will exist inside the body of the let. Implicitly, all the expressions in the let form are packed inside a begin, and the end result of the whole expression is the final expression. Notice that one binding cannot refer to the others in the definition part; if one variable needs to refer to previous definitions, then use a let*:

(let* ((x 10)
       (y (* x 2)))
  (+ x y))

=> 30

Finally, if you need to create a recursive definition use letrec:

(letrec ((fact (lambda (x)
                 (if (zero? x) 1 (* x (fact (sub1 x)))))))
  (fact 10))

=> 3628800



回答2:


You could make a procedure like you proposed:

(define (test var)
  (display var)
  var)
(test (negate (test vara)))) ; prints our argument and return

Or you could use DrRacket and use the debugger. You'll miss it after using it once!



来源:https://stackoverflow.com/questions/13694416/scheme-storing-the-result-of-a-function-let

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!