所以我使用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
:
这是我现在使用的代码:
(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))))))
答案 0 :(得分: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 ..... ))))
那就是那个!
答案 1 :(得分: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))))
max等于当前事物中的最高数字 level是同一形状中最简单(读取最低值)事物中的最高数字(即(事物(事物5 6)(事物7 8))最大值为8,等级为4)
(define (build-thing-or-number n)
(cond
((= n 1) 1)
(else (helper n n))))
正如您所看到的,帮助者完成所有工作。