Skip to content

Instantly share code, notes, and snippets.

@gintenlabo
Last active December 15, 2015 19:19
Show Gist options
  • Select an option

  • Save gintenlabo/5310913 to your computer and use it in GitHub Desktop.

Select an option

Save gintenlabo/5310913 to your computer and use it in GitHub Desktop.
import Data.List (minimum)
import Data.Function (on)
import Data.Ratio ((%))
-- return minimum element compared by given function
-- (return value used by compare, too)
-- another implementation (more generic ver.)
newtype CompOnSnd a b = CompOnSnd { fromCompOnSnd :: (a, b) }
-- for implementation, get snd from CompOnSnd
sndFromCompOnSnd = snd . fromCompOnSnd
instance Eq b => Eq (CompOnSnd a b) where
(==) = (==) `on` sndFromCompOnSnd
instance Ord b => Ord (CompOnSnd a b) where
compare = compare `on` sndFromCompOnSnd
minimumOn :: (Ord b) => (a -> b) -> [a] -> (a, b)
minimumOn f xs = fromCompOnSnd $ minimum $ [ CompOnSnd (x, f x) | x <- xs ]
main = do
let xs = [(1, 2), (2, 3), (4, 5)]
print $ minimumOn (\(a, b) -> a % b) xs
import Data.List (minimumBy)
import Data.Function (on)
import Data.Ratio ((%))
-- return minimum element compared by given function
-- (return value used by compare, too)
minimumOn :: (Ord b) => (a -> b) -> [a] -> (a, b)
minimumOn f xs = minimumBy (compare `on` snd) $ [(x, f x) | x <- xs]
main = do
let xs = [(1, 2), (2, 3), (4, 5)]
print $ minimumOn (\(a, b) -> a % b) xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment