for loop in scheme

我只是一个虾纸丫 提交于 2019-12-24 08:34:26

问题


i'm kinda of confused how i can construct a for loop in scheme. the for-loop should be implemented in Part II. where it takes a list of numbers and insert each element inside the list in Part I to find the length. I was cable to get the first element but i need a for loop or what so ever to get an output like this: '(7 10 5 16 106 37) here is my code :

#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))

here is the output :

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

回答1:


Let me get this straight, you need the length of the Collatz sequence for each of the numbers in the items list? Clearly this is homework, so I can't give a straight answer this time. Here's the general structure of the solution, fill-in the blanks:

(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

Test the procedure, the result should be as shown below:

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

Notice that your answer was almost right - the base case for this procedure is simply the empty list, and you forgot to call the recursion. In Scheme, at least for know, try not to think about while, for loops: implement iteration in terms of recursion, that's the idiomatic way to do it. After you get that straight, you can start using one of the built-in looping constructs available in Racket.




回答2:


I dont want to give the exact answer but you can iterate the whole list and find this length like this.

(define (length lst)
(if (null? items)
'()
(+ 1  (length(cdr lst)))))

With this way you access the all elements of the list recursively. It finds the first element adds +1 and then it tries to find the length of cdr list which is equal to length lst-1. It does this until it reaches to the end of the list.



来源:https://stackoverflow.com/questions/14883062/for-loop-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!