How does `let` work in Scheme?

2019-04-08 08:08发布

I use let to create a temporary variable, and then use this temporary variable in the next statement. However, DrScheme complained,

let: bad syntax (not an identifier and expression for a binding) in: temp

This is my code snippet:

(define (case-one-helper str)
  (let (temp (substring str (+ 3 (string-contains str "my"))))
    (substring temp (string-contains temp " "))))

I wonder if the value of variable created by let has to be known at compiled time?

Edit I've just figured out, missing ().

Thanks,

标签: scheme
2条回答
做个烂人
2楼-- · 2019-04-08 08:27

You need to put another set of parentheses around your let declarations:

(define (case-one-helper str)
  (let ((temp (substring str (+ 3 (string-contains str "my")))))
    (substring temp (string-contains temp " "))))
查看更多
在下西门庆
3楼-- · 2019-04-08 08:36

While not exactly the problem you're experiencing, but an aside based on your questioning about the sequence of evaluating the arguments, let is also "syntactic sugar" for a lambda followed by it's arguments that are first evaluated and then passed to the lambda which is then evaluated.

For instance:

(let ((a (list 1 2 3))
      (b (list 4 5 6)))
     (cons a b))

is the same as:

((lambda (list-a list-b) (cons list-a list-b)) (list 1 2 3) (list 4 5 6))

So, if you're ever wondering about evaluation sequence, the arguments are evaluated fully before the body is evaluated (and one argument cannot refer to an argument preceding it ... use let* for something that requires bindings like that).

查看更多
登录 后发表回答