I am trying to make a simple function in scheme that finds the largest number in a list.
Here is my code:
(define (maximo lista maximo_actual)
(if (= lista ())
maximo_actual
(let* ((primero maximo_actual)
(segundo (car lista)))
(if (> primero segundo)
((maximo (cdr lista) primero))
((maximo (cdr lista) segundo))))))
I call the function with this:
(maximo (list 6 3 2 8 9) 5)
And the program return this:
;ERROR: "programas.scm": =: Wrong type in arg1 (6 3 2 8 9)
; in expression: (#@= #@lista ())
; in scope:
; (lista maximo_actual) procedure maximo
; defined by load: "programas.scm"
I think that there is something wrong with the parameters. I am learning scheme and I don’t know where the problem is.
My awnser here is based on Racket (which is based on scheme)
There are a few issues with your program. One,
=compares numbers, not lists. Secondly()is a function with nothing in it, not a list. To create an empty list use either(list)or'(). Finally,((maximo (cdr lista) primero))has an extra set of parenthesis, which causes the result of(maximo (cdr lista) primero)to be executed. However, the result of(maximo (cdr lista) primero)is a number.I think you want something like this, which will return
9when called with(maximo (list 6 3 2 8 9) 5)You could also write it using fold, which is slightly shorter: