Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a list as parameter function?

Tags:

scheme

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.

like image 273
kentverger Avatar asked Mar 18 '26 15:03

kentverger


1 Answers

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 9 when called with (maximo (list 6 3 2 8 9) 5)

(define (maximo lista maximo_actual)
    (if (empty? lista)
        maximo_actual
        (let* ((primero maximo_actual)
                (segundo (car lista)))
            (if ( > primero segundo)
                (maximo (cdr lista) primero)
                (maximo (cdr lista) segundo)))))

You could also write it using fold, which is slightly shorter:

(define (maxio2 current result)
  (if (> current result)
      current
      result))

(foldl maxio2 5 (list 6 3 2 8 9))
like image 88
Jake Walsh Avatar answered Mar 24 '26 23:03

Jake Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!