无法返回最深的一对列表

时间:2019-11-25 04:11:26

标签: scheme racket

#lang racket
(define (depth L)
  (cond ((null? L) 0) ;if list is null return 0, base case
  ((not(list? L)) 0) ;if list is just an atom also return 0, also a base case
  (else (max (+ 1 (depth(car L))) (depth(cdr L)))))) ;otherwise return the greater of recursive call (depth(car list)) +1 or (depth(cdr list))
  ;the logic here using findMax is that to see which one of the recursion is deeper, and everytime car is called we add 1 to the depth

我试图实现一种方案来查找列表的最大深度,但是它需要返回最深列表以及深度本身,而且我不是如何实现返回最深对的函数。

例如:

(display(max-depth  '( (a b)(b d e (f  g))(r(s (u v (m n))))(q (p))  )    ))
return ((m n) 4) 

1 个答案:

答案 0 :(得分:1)

#lang racket

; an Atom is:
; - Number | Symbol | String | ...

; an S-expr is one of:
; - Atom
; - SL

; an SL is one of:
; - '()
; - (cons S-expr SL)


; Atom -> Boolean
; is x an atom?
(define (atom? x)
  (and (not (pair? x)) (not (null? x))))

; A MyPair is a structure
;   (pair X Y)
(struct my-pair (fst snd) #:transparent)

; S-expr -> Pair
; depth of & deepest pair in s-expr
(define (sexpr-deepest s-expr)
  (cond [(atom? s-expr) (my-pair 0 (list s-expr))]
        [(list? s-expr) (sl-deepest s-expr)]))

; SL -> Pair
(define (sl-deepest sl)
  (cond [(empty? sl) (my-pair 0 sl)]
        [(cons? sl) (if (andmap atom? sl)
                        (my-pair 1 sl)
                        (first-pair-vs-rest-pair (sexpr-deepest (first sl))
                                                 (sl-deepest (rest sl))))]))
; Pair Pair -> Pair
(define (first-pair-vs-rest-pair p1 p2)
  (if (>= (add1 (my-pair-fst p1)) (my-pair-fst p2))
      (my-pair (add1 (my-pair-fst p1)) (my-pair-snd p1))
      (my-pair (my-pair-fst p2) (my-pair-snd p2))))


(module+ test
  (require rackunit)

  (check-equal? (sexpr-deepest '((a b) (b d e (f g)) (r (s (u v (m n)))) (q (p))))
               (my-pair 5 '(m n)))

  (check-equal? (sexpr-deepest '((asd) (a (d (f (w)))) ((d))))
               (my-pair 5 '(w)))

  (check-equal? (sexpr-deepest '(a (((b c d))) (e) ((f)) g))
               (my-pair 4 '(b c d))))