Created
February 3, 2011 09:15
-
-
Save shangaslammi/809248 to your computer and use it in GitHub Desktop.
Sample implementation of KataPotter (http://codingdojo.org/cgi-bin/wiki.pl?KataPotter) in Haskell (FYI, it's my first program in Haskell, so it might not be all that idiomatic)
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 List | |
import Array | |
import System (getArgs) | |
discounts = listArray (1,5) ([1.0, 0.95, 0.9, 0.8, 0.75]::[Float]) | |
bookPrice = 8.0::Float | |
grouped :: Ord a => [a] -> [Int] | |
grouped = sort . (map length) . group . sort | |
variations :: [Int] -> [[Int]] | |
variations = takeWhile (not . null) . iterate (sort . next) | |
where next (1:x:xs) = (x+1):xs | |
next (x:x':xs) = (x-1):(x'+1):xs | |
next _ = [] | |
groupedPrice :: [Int] -> Float | |
groupedPrice = minimum . map (variationPrice) . variations | |
where variationPrice = sum . map (priceOfSet) . toSets | |
priceOfSet s = bookPrice * (fromIntegral s) * (discounts ! s) | |
toSets [] = [] | |
toSets xs = replicate (head xs) (length xs) ++ rest | |
where rest = toSets $ map (subtract (head xs)) $ tail xs | |
orderPrice :: Ord a => [a] -> Float | |
orderPrice = groupedPrice . grouped | |
main = do | |
args <- getArgs | |
print $ argPrice args | |
where argPrice = groupedPrice . sort . map read |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment