Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Racket function for finding minimum element of list given a function

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?

like image 350
colos_enough Avatar asked Mar 02 '23 04:03

colos_enough


2 Answers

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.

like image 102
Sorawee Porncharoenwase Avatar answered Apr 30 '23 08:04

Sorawee Porncharoenwase


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]

like image 36
mindthief Avatar answered Apr 30 '23 08:04

mindthief