getting the largest number in a list in scheme

前端 未结 6 1720
长发绾君心
长发绾君心 2021-01-23 23:00

I do not understand why my function to get the largest number does not want to work. If I am thinking about this correctly, if the first atom is smaller than the second atom the

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 23:40

    There are 2 errors in your code:

    1) in the else clause, you should recursively call yourself, dropping the second element:

    (else (getlargest (cons (car a_list) (cddr a_list))))))
    

    2) you are missing the case of a list of only one element, where cadr will fail

    ((null? (cdr a_list)) (car a_list))
    

    And I personally prefer to yield #f if the list is empty. Thus the code would look like

    (define (getlargest a_list)
      (cond
        ((null? a_list)       
         #f)
        ((null? (cdr a_list))
         (car a_list))
        ((< (car a_list) (cadr a_list))
         (getlargest (cdr a_list)))
        (else 
         (getlargest (cons (car a_list) (cddr a_list))))))
    

    Of course, a solution using foldl is preferable:

    (define (getlargest lst)
      (foldl (lambda (e r) (if (or (not r) (> e r)) e r))
             #f
             lst))
    

    or, probably slightly more efficient:

    (define (getlargest lst)
      (if (null? lst)
          #f
          (foldl (lambda (e r) (if (> e r) e r))
                 (car lst)
                 (cdr lst))))
    

提交回复
热议问题