loops - for循环方案

标签 loops lisp scheme racket collatz

我有点困惑如何在方案中构建 for 循环。 for循环应该在第二部分中实现。它需要一个数字列表并将每个元素插入第 I 部分中的列表中以查找长度。我很想获得第一个元素,但我需要一个 for 循环或其他任何东西来获得这样的输出:'(7 10 5 16 106 37) 这是我的代码:

#lang racket
; Part I
(define (sequence n)
(cond  [(= n 1)
      (list n)]
[(even? n)
( cons n(sequence( / n 2)))]
[(odd? n) 
( cons n(sequence (+(* n 3) 1))) ] ))

(sequence 3)

; Part II
(define (find-length items)
( cond [(null? items)
      (list items)]
  [find-length(length(sequence(car items))) ]   
  ))

  (find-length '(10 13 16 22 95 158))

这是输出:

 '(3 10 5 16 8 4 2 1)
 7

最佳答案

让我直截了本地说,您需要 items 列表中每个数字的 Collat​​z 序列的长度?显然这是作业,所以这次我不能直接回答。这是解决方案的一般结构,填空:

(define (find-length items)
  (if (null? items)           ; if the list is null
      <???>                   ; return the empty list
      (cons                   ; otherwise `cons` the
       (length <???>)         ; length of Collatz sequence of first element
       (find-length <???>)))) ; and recur over the rest of the list

测试程序,结果如下图所示:

(find-length '(10 13 16 22 95 158))
=> '(7 10 5 16 106 37)

请注意,您的答案几乎是正确的 - 此过程的基本情况只是空列表,而您忘记调用递归。在 Scheme 中,至少要知道,尽量不要考虑 while、for 循环:根据递归实现迭代,这是惯用的方法。弄清楚之后,您可以开始使用内置的 looping constructs 之一。在 Racket 中可用。

关于loops - for循环方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14883062/

相关文章:

performance - Perl 中的慢循环

lisp - 你能在 LISP 中使用 'list' 命令获得点表示吗?

lisp - 为什么使用 cons 创建一对两个列表会产生一个列表和两个元素?

javascript 循环 getElementById

Javascript - 确保地理编码器循环在嵌套循环之前完成,从而导致 markCluster 出现问题

Python:随机数

scheme - 这是尾递归吗?

lisp - 了解包加载

c# - C# 中的通用 Func<> 类型

scheme - 如何在 Racket 列表中添加