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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With