Quote:
Original post by Muhammad Haggag
These are my solutions to 2.29. Again, I feel they're not elegant enough. Specifically, branch-structure and mobile-balanced? look really kludgy.
*** Source Snippet Removed ***
The solution for 2.29-d (replacing lists with cons cells, i.e. list with cons and list? with pair?):
*** Source Snippet Removed ***
Detail: a function
(define (left-branch mobile) (car mobile))
can also be defined as
(define left-branch car)
If find your definition of branch-structure suspect: if the constructor looks like (list x1 x2), the accessors should be no more complex than car and cadr. Also, as all branches you create are lists of length 2, the check does not do anything, as the cdr of a 2-item list will always have length 1.
I don't like branch-weight too much, it breaks the layers of abstraction. The lowest abstraction layer consists of the constructors and accessors, and higher level functions built upon this lowest layer should never know about the internals. In your case, you know that you have to use list? in order to know if a structure is a number or another mobile.
I would add predicate functions in the lowest layer to avoid this: number-structure? and mobile-structure?. Notice what these predicates actually do: given a
structure (important precondition), they will be able to identify if it is either a number or a mobile. I don't really like this, as I could give it a branch and it'd return #t without complaining. You can avoid this by adding type tags, e.g. the constructor becomes (list 'mobile left-branch right-branch), but that would be deviating from the exercise.
Same criticism applies on mobile-balanced?.
Also, you can make it a bit more elegant also by noticing that (if cond a #t) is the same as (or (not cond) a), which in your case would result in
(or (number? (branch-structure lb)) (mobile-balanced? (branch-structure lb)))
or more abstract
(or (number-structure? (branch-structure lb)) (mobile-balanced? (branch-structure lb)))
Part d of the exercise: changing the representation ought only to have repercussion on the lowest level (constructors, accessors, predicates). This is not the case in your code as branch-weight and mobile-balanced? had to be modified.
Try to stratify your code as much as you can, in any language. It really helps a lot.
[Edited by - SamLowry on June 24, 2007 2:15:30 PM]