lisp - 处理列表和附加值的开始方案 (LISP)

标签 lisp scheme racket

我正在尝试创建一个函数,该函数接受 2 个数字,并将创建一个列表,使用第一个数字作为起始数字,第二个数字作为结束值,同时填充起始数字和结束数字之间的值。

例如:

用户传入 3 和 7:

输出应该是 (3 4 5 6)

我试图这样做并使用递归,但我很挣扎:

 (define (createlist start end)
   (if(= start end)
      '())
   (cons start '())
    (createlist (+ 1 start) end))

最佳答案

在此类问题的解决方案中发现了一个重复模式,您必须在使用递归的过程中构建一个列表。让我来说明一般步骤,我会让你填空:

(define (createlist start end)
  (if (= <???> <???>) ; the problem is solved when start and end are the same
      '()             ; lists end in null
      (cons <???>  ; if we are not done yet, we `cons` the current value of start
            (createlist <???> end)))) ; with the result of calling the recursion
            ; notice that start is one step closer to the end, so we increment it

该算法的思想是在每一步我们添加当前的 start使用 cons 构建的列表的值, 并递增 start直到它到达 end , 至此递归结束。

你应该看看 The Little SchemerHow to Design Programs ,这两本书都会教你如何为这种列表递归问题构建解决方案。

更新:

现在您已经发布了到目前为止编写的代码,我可以告诉您正确答案。请非常小心括号 [ if 的右括号在 else 之后部分 ] 和空格 [ if(if ( 不同],它们在 Scheme 中很重要。正确缩进你的代码,它会帮助你找到很多错误:

(define (createlist start end)
  (if (= start end)
      '()
      (cons start
            (createlist (+ 1 start) end))))

现在你可以看到 <???>正确填写。

关于lisp - 处理列表和附加值的开始方案 (LISP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719787/

相关文章:

javascript - 是否有用于在浏览器中呈现的 Scheme 语言的语法高亮插件?

loops - 在 Racket 中通过循环附加的正确方法是什么?

scheme - 在 Racket 中的宏扩展期间评估表单

scheme - 如何在Scheme中进行模式匹配?

dependencies - 如何管理常见的 lisp 依赖项?

recursion - 使用递归在 Lisp 中生成斐波那契数列?

lisp - 设置,不在 Lisp 世界中列出?

map - Scheme中的for-each和map

windows - 我无法在 Windows 上设置和配置 Common LISP (SBCL)

python - 是否有一些与 Python 无缝集成的 lispy 语言?