获取方案中列表中的最大数字 [英] getting the largest number in a list in scheme

查看:44
本文介绍了获取方案中列表中的最大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我的获取最大数字的函数不起作用.如果我的想法是正确的,如果第一个原子小于第二个原子,那么你调用函数减去列表中的第一个,否则你用列表的其余部分构造第一个原子,最大的一个.相关代码:

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 then you call the function minus the first one in the list, else you construct the first atom, largest one, with the rest of the list. relevant code:

(define (getlargest a_list)
  (cond
    ((null? a_list) '())
    ((< (car a_list) (cadr a_list)) (getlargest (cdr a_list)))
    (else (cons (car a_list) (getlargest(cdr a_list))))))

推荐答案

您当前的过程在运行时失败.即使没有,您也将一个元素与下一个元素进行比较,但这不适用于查找最大值,例如在这样的列表中,它将返回 1,其中不正确:'(10 2 0 1).例如,还有其他错误 - 为什么要构建列表作为输出,而答案应该是数字?您还必须非常小心边缘情况,当列表中只剩下一个元素时,您的程序就会失败.

Your current procedure is failing at runtime. Even if it didn't, you're comparing one element with the next, but that won't work for finding a maximum, for instance in a list such as this it'll return 1, which is incorrect: '(10 2 0 1). There are other mistakes, for instance - why are you building a list as output, when the answer should be a number? also you have to be very careful with the edge cases, your procedure is failing when there's a single element left in the list.

正确的方法是将一个假定为最大值的元素与其他所有元素进行比较,如果我们发现一个大于假定最大值的元素,那么我们就找到了一个新的最大值.这就是我的意思:

The correct way is to compare one element assumed to be the maximum with all the rest, if we find one that is greater than the assumed maximum, then we've found a new maximum. This is what I mean:

(define (getlargest a_list)
  (if (null? a_list) ; edge case: empty list
      #f             ; return a special value signaling error   
      (let loop ((a_list (cdr a_list))   ; rest of the list
                 (maxval (car a_list)))  ; assumed maximum
        (cond ((null? a_list) maxval)    ; if the list is empty, return max
              ((> (car a_list) maxval)   ; current element > max
               (loop (cdr a_list) (car a_list))) ; found new max
              (else                      ; otherwise
               (loop (cdr a_list) maxval))))))   ; keep the same max

当然,在现实生活中,我们会出于同样的目的使用内置的 max 过程:

Of course, in real life we would use the built-in max procedure for the same purpose:

(apply max a_list)

这篇关于获取方案中列表中的最大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆