For a loop in a circuit

I am a little confused how I can build a for loop in a schema. the for loop should be implemented in Part II. where it takes a list of numbers and inserts each element inside the list into Part I to find the length. I was cabled to get the first element, but I needed a for loop or something similar 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 result:

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

      

+1


source to share


2 answers


Let me get this straight, do you need the Collatz sequence length for each of the numbers in the list items

? 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

      

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



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

      

Note that your answer was almost correct - the base example for this procedure is just an empty list and you forgot to call recursion. In Scheme, at least for the sake of knowing, try not to think about it, as for loops: implementing iteration in terms of recursion is the idiomatic way to do it. Once you get this straight, you can start using one of the built-in string constructs available in Racket.

+4


source


I don't want to give an exact answer, but you can iterate over the whole list and find this length as follows.

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

      



This way, you recursively access all the elements of the list. It finds that the first element is adding +1

and then tries to find the length of the list cdr

, which is length lst-1

. He does this until he reaches the end of the list.

0


source







All Articles