【问题标题】:scheme : delay and force for interactive I/O方案:交互式 I/O 的延迟和强制
【发布时间】:2013-04-08 20:27:01
【问题描述】:

首先我会提出问题。

假设将输入定义为一个返回“istream”的函数 - 一个承诺,当强制执行时将产生一对,其 cdr 是 istream:

(define input (lambda () (delay (cons (read) (input)))))

现在我们可以将驱动程序定义为期望一个“ostream”——一个空列表或一对,其中的 cdr 是一个 ostream:

(define driver
  (lambda (s)
    (if (null? s) '()
      (begin
      (display (car s))
      (driver (force (cdr s)))))))

注意使用武力。

展示如何编写函数 squares,使其接受 istream 作为参数并返回 ostream。然后您应该能够输入 (driver (squares (input))) 并查看相应的行为。

书上的方块在上面。

(define squares (lambda (a)
  (cons "please enter a number\n"
    (let ((n (car a)))
      (if (eof-object? n) '()
        (cons (* n n) (cons #\newline (squares (cdr a)))))))))

(define output (squares (input)))

我不知道如何解决它以及我可以从哪里开始。请帮忙。

【问题讨论】:

    标签: scheme


    【解决方案1】:

    以下是解决方案。 (注意:力是作为驱动程序功能的一部分完成的)。要理解的重要一点是,“流”函数(输入、正方形)返回一个延迟表达式,它是一对 2 项,其中第 2 项是另一个延迟表达式,依此类推,force 函数也适用于正常值因此squares 的最后一部分返回 3 个缺点。

    (define input (lambda () (delay (cons (read) (input)))))
    
    (define driver
      (lambda (s)
         (let ((s (force s)))
           (if (null? s) '()
               (begin
                (display (car s))
                (flush-output)
                (driver (force (cdr s))))))))
    
    
    (define squares
      (lambda (a)
         (delay (cons "please enter a number\n"
                  (delay (let ((nums (force a)))
                           (if (null? (car nums)) '()
                               (cons (* (car nums)
                                        (car nums))
                                     (cons #\newline (squares (cdr nums)))))))))))
    

    现在您可以像这样运行它:(driver (squares (input)))。要退出提示,用户需要输入空列表()

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多