4

Is there some function in Racket(Scheme) that can give me the element, which produces the minimum value after applying a given function in a list. Something like (apply min (map f list)) but returning the element before applying f. For example:

(define lst '((1 . 3) (3 . 8) (5 . 6))
(define (f pair)
  (- (cdr pair) (car pair)))
(minimum f lst)

This should give '(5 . 6).

There should be a one liner for this with higher order functions at least if there is no direct function(as I had to fill in one line to get this behaviour). Any ideas?

0

2 Answers 2

6

Try argmin:

#lang racket

(define lst '((1 . 3) (3 . 8) (5 . 6)))
(define (f pair)
  (- (cdr pair) (car pair)))
(argmin f lst)

produces '(5 . 6) as you desired.

Sign up to request clarification or add additional context in comments.

Comments

2

You could use this generic version of min, which accepts a key argument:

(require relation)
(apply min #:key f lst)

=> '(5 . 6)

This version of min also works on strings or any other orderable type (i.e. not just numbers).

[disclosure: I'm the author of this library]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.