Skip to content

Instantly share code, notes, and snippets.

@KevOrr
Created May 15, 2018 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevOrr/aee3fbe0f01dc1be761f781328547d20 to your computer and use it in GitHub Desktop.
Save KevOrr/aee3fbe0f01dc1be761f781328547d20 to your computer and use it in GitHub Desktop.
Take n largest items Haskell
module CodeWars.Largest (largest) where
import Data.List (sortBy, sort)
import Data.Ord (comparing, Down)
largest :: Ord a => Int -> [a] -> [a]
largest n xs = sort $ take n $ sortBy (comparing Down) xs
-- Line 6 causes compilation error:
-- • Data constructor not in scope: Down :: a -> a0
-- • Perhaps you want to add ‘Down’ to the import list
-- in the import of ‘Data.Ord’ (/tmp/flycheck15029c7f:3:1-33).
-- | (haskell-stack-ghc)
module CodeWars.Largest (largest) where
import Data.List (sortBy, sort)
import Data.Ord (Ordering)
compDown :: Ord a => a -> a -> Ordering
compDown a b = case (compare a b) of
LT -> GT
EQ -> EQ
GT -> LT
largest :: Ord a => Int -> [a] -> [a]
largest n xs = sort $ take n $ sortBy compDown xs
-- This version works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment