Scheme 从给定列表中查找Collatz序列的最大值
我对scheme语法是新手。 这是我一直在做的项目的最后一部分。 我能够从给定的Collatz序列中找到最大长度,但项目的这一部分需要从多个Collatz序列列表中找到最大长度。 例如,给出这个列表:‘(110)(10200)(201210)(9001000),输出应该是这样的:‘(2012589174) 我需要找到数字1到10之间的最大长度,然后是10到200之间的最大长度 这是我的密码:Scheme 从给定列表中查找Collatz序列的最大值,scheme,sequence,collatz,Scheme,Sequence,Collatz,我对scheme语法是新手。 这是我一直在做的项目的最后一部分。 我能够从给定的Collatz序列中找到最大长度,但项目的这一部分需要从多个Collatz序列列表中找到最大长度。 例如,给出这个列表:‘(110)(10200)(201210)(9001000),输出应该是这样的:‘(2012589174) 我需要找到数字1到10之间的最大长度,然后是10到200之间的最大长度 这是我的密码: #lang racket ; Part I (define (sequence n) (cond
#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 10)
; Part II
(define (find-length items)
(if (null? items)
(list )
(cons
(length (sequence(car items)))
(find-length (rest items))))
)
(find-length (list 10 16 22 90 123 169))
;Part III
(define max-in-list (lambda (ls)
(let ( (head (car ls)) (tail (cdr ls)))
(if (null? tail)
; list contains only one item, return it
head
; else find largest item in tail
(let ((max-in-tail (max-in-list tail)))
; return the larger of 'head' and 'max-in-tail'
(if (> head max-in-tail)
head
max-in-tail
)
)
)
)
))
(define (find-max i j)
( if (= i j)
(list)
(cons
(max-in-list (find-length(sequence i)))
(find-max (+ 1 i ) j)
))
)
(max-in-list(find-max 1 10))
(define (max-length-list items )
(if (null? items)
(list)
(cons
(find-max ? ?) ) ; how i can call this function ?
(max-length-list (?) ) ; how i can call this function ?
)))
(max-length-list '((1 10) (10 200) (201 210) (900 1000) ))
传递给
最大长度列表的列表中的每个项目都是一个包含两个数字和一个nil
的列表,例如(cons 1(cons 2'())
第一个数字是(汽车(汽车项目))
第二个是(汽车(cdr(汽车项目))
或者,如果您让((车头(汽车项目))
,则它们是(车头)
和(汽车(cdr车头))
递归调用很简单;您已经用find max
处理了第一个元素,现在您只需要处理其余的元素。显然,您已经知道如何实现这一点,因为您已经做到了。1.您还没有告诉我们什么是“Collatz”序列意味着。这是艺术的某个技术术语吗?2.您的函数没有契约,因此很难判断像max-in-list
这样的函数是否格式正确(例如,它是否需要处理空列表?).但当然,3.您还没有编写任何数据定义,因此很难判断您的程序要操作的数据类别。(数字列表?数字元组列表?)我猜,在编写许多合同之前,您需要先编写这些数据定义。谢谢,我对第二个元素感到困惑,而这(car(cdr(car items))起到了神奇的作用