2017-09-27 11 views
3
DrRacket(またはスキーム)でこの形式のツリーを

形成は、だから私はDrRacketを使用して、以下のように定義構造体を持っています

(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)))) 

- 私はどのように把握することができました

ここで今私が使用するコードです:

(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の最大および4)

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

のレベルを持って、ヘルパーは、すべての作業を行います。

+0

これも完璧に動作します。アップアップされました! – abcd

+0

透明感のある素敵なタッチ。 –

関連する問題