Last active
December 15, 2015 19:19
-
-
Save gintenlabo/5310913 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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