HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

This snippet of scheme calculates a value in pascal's triangle

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thissnippetschemepascalvaluetrianglecalculates

Problem

I'm working through SICP and have implemented exercise 1.11 (Pascal's Triangle). What I'm curious about here is performance considerations by defining functions within the main function. I would assume they get reassigned with each invocation of the function. In saying that, this style appeals to me, as the functionality is scoped to the main function, and lexical scoping is used to effect. Obviously I'm a scheme noob so please go nuts in tearing this code apart.

(define (pascal-value row elem)  

  (define (out-of-range?)  
    (or (> elem row) (< elem 1)))

  (define (edge?)
    (or (= row elem) (= elem 1)))

  (cond ((edge?) 1)
        ((out-of-range?) 0)
        (else (+ (pascal-value (- row 1) (- elem 1)) 
                 (pascal-value (- row 1) elem)))))

Solution

Yes, those inner functions do get reassigned at each invocation, but that's cheap. In sane implementations, the inner function bodies are compiled just once, with a new lexical environment attached each time.

(In other sane implementations, the inner functions could be inlined into the outer function, but still, it's only compiled once, not for every invocation.)

So don't worry about the performance, it's not as bad as you may think. :-)

Context

StackExchange Code Review Q#51314, answer score: 5

Revisions (0)

No revisions yet.