简体   繁体   中英

In racket, built in function to tell what position a variable is in

I have two lists, one of symbols and one of numbers. I need to find the maximum of the list of numbers and output the associated symbol. I have a way to find the maximum, but seem unable to also fit in the first list.

So is there a way to input a number and a lit, and it tells what position the number is in? So then I can use list-ref on the list of symbols to find the proper symbol?

Unless someone can help me with the above problem to put it all in one function? I have this outline:

(define (max-list lon)
  (cond [(empty? (rest lon)) (first lon)]
        [(> (first lon) (max-list (rest lon))) (first lon)]
        [else (max-list (rest lon))]))

to find the max-value for the list of numbers.

You can use the argmax function to do this conveniently. You can use map with cons to "zip" the two lists into a series of pairs, then pass the result into argmax to find the pair you want.

(define num-list '(4 8 2 7))
(define sym-list '(a b c d))

(cdr (argmax car (map cons num-list sym-list)))
; => 'b

The way argmax works is that it takes an "optimizer" procedure that returns a numeric value for each element of the list, and the result of the function is the first element that maximizes the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM