Uri Goren Uri Goren - 1 month ago 14
Python Question

Implementing argmax in Haskell

Given a list

L
, and a function
f
, I want to return an item
x
from
L
that maximizes the value of
f(x)


I cam up with this code for 2 variables:

argmax f x y = if (f x) > (f y) then x else y


How can this be generalized to

argmax f [x,y,z]


(With an arbitrary number of items in the list)

This is what I would do in
Python
:

argmax = lambda f,L: max([(f(x),x) for x in L])[1] if len(L)>0 else None


How can I apply the same logic in
Haskell
?

Answer

Disclaimer -- I've been learning Haskell (functional paradigm in general) for a week now so it's likely there are better solutions.

import Data.Ord
import Data.List

argmax f l 
    | null l = error "Given list is empty"
    | otherwise = maximumBy (comparing f) l