2016-12-18 6 views
0

나는 exp 또는 중첩 된 목록에 el이 표시되는지 확인하기 위해 이상을 입력하고 I ' 내가 관련 특급에 얼마나 많은 엘의 경우 계산과 함께 모든 합계하지만 난 카운터를 추가하고 모든 재귀 호출을해야한다 생각스키마 - 요소가 표현식이나 중첩 된 표현식에 두 번 이상 표시되는지 여부를 확인하는 함수

(define appearInExp? 
    (lambda (el exp) 
     (let ((found?  (ormap (lambda (e) (equal? el e)) exp)) 
       (listsLeft? (ormap (lambda (e) (list? e)) exp)) 
       (lists (filter (lambda (e) (list? e)) exp))) 

     (if found? 
      #t 
      (if (not listsLeft?) 
       #f 
       (let ((elList (extendList el (length lists)))) 
        (ormap appearInExp? elList lists))))))) 



    *help function:* 

    (define extendList 
     (lambda (el num) 
      (if (equal? num 1) 
       `(,el) 
       `(,el ,@(extendList el (- num 1)))))) 

**tests: 
(appearInExp? '3 '(1 2 3))    ---> #t 
(appearInExp? '3 '(1 2 '(3)))   ---> #t 
(appearInExp? '3 '(1 2 '(1 2 ((3))))) ---> #t 

: m 문제가 두 번를 확인하는 방법을 이해하는 데 그렇게하는 데 문제가 있습니다.

당신의 도움은 대단히 감사하겠습니다.

답변

1

다음 작품들. 그것은 카운터의 모든 항목을 통과하는 카운터와 루프를 가지고 있습니다. 항목이 목록의 경우, 함수는 recusively 호출됩니다

(define (appearInExp? el exp) 
    (let loop ((exp exp) 
      (c 0)) 
    (cond 
     [(empty? exp) c] 
     [(list? (first exp)) 
     (loop (rest exp) 
      (+ c (appearInExp? el (first exp))))] 
     [(equal? el (first exp)) 
     (loop (rest exp) (add1 c))] 
     [else 
     (loop (rest exp) c)]))) 

(appearInExp? '2 '(1 2 3)) 
(appearInExp? '2 '(1 2 '(2 3))) 
(appearInExp? '2 '(1 2 '(1 2 ((3 2))))) 

출력 : 당신이 걸릴 수

1 
2 
3 
0

또 다른 방법은 목록을 평평하게하는 것입니다.

(define (flatten lst) 
    (cond [(empty? lst) empty] 
     [(number? (first lst)) (cons (first lst) (flatten (rest lst)))] 
     [else (append (flatten (first lst)) (flatten (rest lst)))])) 

(define (f/acc n lst counter) 
    (cond [(empty? lst) counter)] 
     [(= n (first lst)) (f n lst (add1 counter))] 
     [else (f n lst counter)])) 

(define (f n lst) 
    (f/acc n lst 0))