How to write Scheme (R5RS languages) program to count max depth (not using max function)?

StackOverflow https://stackoverflow.com/questions/13676784

  •  04-12-2021
  •  | 
  •  

Question

Here's what I have for the depth program, but how to do it without max function (only use define, lambda,quote (‘), car, cdr, cons, cond, eq?, and equal?)?

(define depth
     (lambda (expr)
        (cond ((null? expr) 0) 
              ((list? (car expr)) 
               (max (+ 1 (depth (car expr))) (depth (cdr expr)))) 
              ((null? (cdr expr))0) (max (depth (cdr expr))))))

input: ((id = id + id)(if bool then (if bool then ( id = id + id ))(id = const / const)(id = id + id))(while bool (id = id - const)(id = id - id)))

Should output: maximumdepth: 2

Was it helpful?

Solution

Well, you can always implement your own my-max and use it instead of the built-in max procedure:

(define (my-max a b)
  (if (> a b) a b))

You'll have to do basically the same comparison, one way or another, for finding the maximum depth - so it's ok to refactor it to a helper procedure. Notice that it wouldn't be a good idea to in-line the comparison, because that would entail evaluating twice the recursive calls - better stick to using a helper procedure, be it max or my-max.

Also, the second call to max is unnecessary in your code - if there's only one value, why do you need to find the maximum?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top