執行一個迭代函數:
(define (collatz x)
(if (even? x)
(/ x 2)
(+ (* x 3) 1)))
這個函數的輸入和循環,直到它達到1.函數返回達到那個狀態(嘗試繪圖爲此所需的迭代次數 - 它看起來很酷):
(define (collatz-loop x)
(if (= x 1) 1
(+ (collatz-loop (collatz x)) 1)))
按照要求,這裏是在Collatz環的尾遞歸版本:
(define (collatz-loop x)
(define (internal x counter)
(if (= x 1) counter
(internal (collatz x) (+ counter 1))))
(internal x 1))
這個函數有一個範圍,並返回需要最多數目的步驟,以與步數沿到達終點的數目:
(define (collatz-range a b)
(if (= a b)
(cons a (collatz-loop a))
(let ((this (collatz-loop a))
(rest (collatz-range (+ a 1) b)))
(if (< this (cdr rest)) rest
(cons a this)))))
(collatz-range 1 20) ; returns (18 . 21), which means that (collatz-loop 18) returns 21
這是在Collatz範圍,尾遞歸:
(define (collatz-range a b)
(define (internal a best)
(if (< b a) best
(internal (+ a 1)
(let ((x (collatz-loop a)))
(if (< x (cdr best))
best
(cons a x))))))
(internal a (cons -1 -1)))
我投票結束這個問題作爲題外話,因爲它是一項功課。 – 2016-03-17 18:16:13