Domanda

I'm kinda new in scheme syntax... I'm trying to make a simple program where you input an integer, if the integer is even do something and if it's odd do something else. I was able to do this part. Now, I need to make a loop where I can decrement the number until it equals to 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 should be a sequence of numbers. In other words, it should be inside a list.

È stato utile?

Soluzione

An output list is built by consing each of the elements that are part of the list and then advancing the recursion over the input, until the input is exhausted (in your case, when the number n is one). By successively consing elements at the head of the list and ending the recursion with a null value, a new proper list is created and returned at the end of the procedure execution. Here's how:

(define (sequence n)
  (cond [(= n 1)                              ; if n=1, it's 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 will return a list with the Collatz sequence 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 have to redefine them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top