我如何将值存储到 Scheme 的读取中?或者那是不可能的?

How would I store a value into read for Scheme? Or is that not even possible?

(define (getFirstFew lst)
  (cond
  ((= (read) 0) '()) ;returns nothing
  (else(cons (car lst)(getFirstFew (cdr lst)(- (read) 1))))))

上面就是我的代码。所以我正在尝试编写一个程序,它将从列表中获取第一个 x 元素(用户可以选择 x 是什么)。例如,使用 (getFirstFew '(1 6 2 4 5)) 输入 4 将导致 '(1 6 2 4)。

我目前的问题是,使用 read 两次,它被调用两次,然后中断程序。有没有办法将用户输入的任何内容存储到变量中,然后在整个程序中使用该变量?或者这个问题有另一种解决方案吗?

请注意,您只需执行 read 一次 一次 ,并存储该值以备将来参考。通常我们使用 let for this, but given that we also have to iterate over the list and decrement x on each iteration, a named let 会更合适。试试这个:

(define (getFirstFew lst)
  (let loop ((lst lst) (x (read)))
    (if (= x 0)
        '()
        (cons (car lst)
              (loop (cdr lst) (- x 1))))))

它按预期工作:

(getFirstFew '(1 6 2 4 5))
> 4
=> '(1 6 2 4)