Cycle diagram

I'm a bit new to schema syntax ... I'm trying to create a simple program where you enter an integer, if the integer even does something, and if it's weird, do something else. I was able to do this part. Now I need to create a loop in which I can decrease the number until it equals 1. Here is my code:

#lang racket

(define (even? n)
  (if (eqv? n 0) #t
         (odd? (- n 1))))
(define (odd? n)
  (if (eqv? n 0) #f
         (even? (- n 1))))

; this is the function that i wanted to be inside the loop
(define (sequence n)
(cond  
[(even? n) n( / n 2)]
[(odd? n) n(+(* n 3) 1) ] )

)
(sequence 5)

      

The output must be a sequence of numbers. In other words, it must be inside the list.

+3


source to share


1 answer


The output list is built by querying each of the elements that are part of the list, and then iterating through the input until the input is exhausted (in your case, when the number n

is one). By sequentially referring to the elements at the head of the list and ending the recursion with a null value, a new correct list is created and returned at the end of the procedure. Here's how:

(define (sequence n)
  (cond [(= n 1)                              ; if n=1, it the  exit condition
         (list n)]                            ; return a list with last element
        [(even? n)                            ; if n is even
         (cons n (sequence (/ n 2)))]         ; cons n and advance the recursion
        [(odd? n)                             ; if n is odd
         (cons n (sequence (+ (* n 3) 1)))])) ; cons n and advance the recursion

      

The above list returns Collatz for the given number n

:



(sequence 6)
=> '(6 3 10 5 16 8 4 2 1)

      

As a side note: the procedures even?

and odd?

are standard in Scheme and you don't need to override them.

+1


source







All Articles