getting the largest number in a list in scheme

前端 未结 6 1771
长发绾君心
长发绾君心 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条回答
  •  旧时难觅i
    2021-01-23 23:35

    First mistake is that you are returning list as output in base case. You need to return a number. You can implement this procedure in recursive way by storing the max value in MaxVal accumulator as we recurse through list.

    Specification

    input : List of positive unique numbers inList

    output : Maximum value in list MaxVal

    Follow is the implementation for above specification:

    Procedure

    (define (GetMaxVal MaxVal inList) 
        (cond ( (null? inList ) MaxVal )
              ( (> (car inList) MaxVal ) (GetMaxVal (car inList) (cdr inList)) ) 
              ( else ( GetMaxVal MaxVal (cdr inList)) ) ))
    
    (define inList '(1 67 3 5 176 4745 34 575)) 
    
    (display (GetMaxVal 0  inList) ) ; prints 4745 to screen
    

    Explaination

    1. If list is empty, we have reached to base case hence return MaxVal
    2. If first element in list is greater than MaxVal than update MaxVal; pass MaxVal and (cdr inList) in argument in recursive call.
    3. else the first element is not greater so recurse by passing list without first element i.e. (cdr inList)

提交回复
热议问题