2017-09-27 33 views
3

所以我用DrRacket,有一個結構定義爲:形成這種格式DrRacket(或計劃)樹

(define-struct thing (a b)) 

然後,我有這種格式的例子樹:

(define v (make-thing 
       (make-thing (make-thing 1 2) 
          (make-thing 3 4)) 
       (make-thing (make-thing 5 6) 
          (make-thing 7 8)))) 

我需要建立一個函數,它接受一個也是2的冪的非正數(如1,2,4,8,16 ...),並輸出數字1(如果n = 1 )或以上述格式製作'東西'。

到目前爲止,我已經嘗試了很多辦法,但我要麼最終得到這樣的:

(make-thing (make-thing (make-thing 1 1) 
         (make-thing 1 1)) 
      (make-thing (make-thing 1 1) 
         (make-thing 1 1)))) 

我無法弄清楚如何正確遞增變量 - 我已經能夠想出如何適用的make-thing S中的所需數量:

下面的代碼我用現在:

(define (helper pow current) 
    (cond 
    ((= pow 0) 1) 
    (else (make-thing 
      (helper (- pow 1) current) 
      (helper (- pow 1) (- current 1)))))) 

(define current 1) 

(define (build-thing-or-number n) 
    (cond 
    ((= n 1) 1) 
    (else (make-thing 
      (helper (- (log n 2) 1) current) 
      (helper (- (log n 2) 1) (add1 current)))))) 

回答

3

請允許我撥打build-thing-or-number只需g,這樣我的打字工作就少了。

所以,你要

(g 1) = 1     ; you've got this covered already 
(g 2) = (thing 1 2) 
(g 4) = (thing (thing 1 2) (thing 3 4)) 
(g 8) = (thing (thing (thing 1 2) (thing 3 4))  ; 1..4 
        (thing (thing 5 6) (thing 7 8)))  ; 5..8 

我們看到,如果我們有更多的參數,這將會是很容易做的:

(define (h a b)      ; from ... to 
    (cond 
    ((= (+ a 1) b)     ; like (h 1 2): 
     (make-thing a b))    ; just make the thing 
    (else        ; e.g. (h 1 4) (h 5 8) 
     (let ([c (/ (+ a b -1) 2)]) ;  c = 2  c = 6 
      (make-thing     ; c is the middle 
       (h a c)    ; make the first half 1..2 1..4 
       (h .....))))))  ; and the second  3..4 5..8 

我們用它簡單地作爲

(define (g b) 
    (cond ((= b 1) 1) 
     (else (h .....)))) 

就是這樣!

+0

感謝您的解釋!這工作得很好 – abcd

2
#lang racket 

(define-struct thing (a b) #:transparent) 

我定義的東西一樣透明,便於覈查

(define (helper level max) 
    (if (equal? (/ level 2) 1) 
     (make-thing (- max 1) max) 
     (make-thing (helper (/ level 2) (- max (/ level 2))) (helper (/ level 2) max)))) 

最大值等於當前的事情 水平最高的數字是在簡單的數量最多(讀最低值)同樣的事情形狀(即(事(事5 6)(7東西8))具有8 max和4個級別)

(define (build-thing-or-number n) 
    (cond 
    ((= n 1) 1) 
    (else (helper n n)))) 

,你可以看到,幫手做所有的工作。

+0

這個作品也很完美。 Upvoted! – abcd

+0

與透明度很好的接觸。 –