Programming performance/Magnus Haskell
- Language: Haskell
- Skill: Intermediate. I'm self taught in Haskell and use it as a hobbyist but haven't used it much for serious work.
- Time: 25 minutes.
- Notes: 10 minutes spent on a silly bug where I had typed 1 instead of 100. This code is not very pretty but it works.
import Data.List (partition,foldl') closingPrice::String->Double closingPrice line = read (words line !! 3) sell assets price = sum (map (\(_,shares)->shares*price) assets) tradeOnce (cash,assets,lastPrice) todayPrice = if todayPrice <= lastPrice * 97/100 then let buyCost = cash*10/100 in (cash-buyCost, (lastPrice,buyCost/lastPrice):assets, todayPrice) else let (toSell,toKeep) = partition (\(buyPrice,_)->todayPrice >= buyPrice*106/100) assets in (cash + sell toSell todayPrice, toKeep, todayPrice) notComment ('#':rest) = False notComment _ = True trade input = let (firstPrice:restPrices) = reverse $ map closingPrice $ filter notComment $ lines input in foldl' tradeOnce (10000.0,,firstPrice) restPrices main = do input <- readFile "gspc.txt" let (cash,toSell,lastPrice) = trade input let result = cash + sell toSell lastPrice print result