HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Programming performance/Magnus Haskell

< Programming performance

Code

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

Bugs: Two minor bugs here. Purchases are made at lastPrice rather than todayPrice. The wrong column of the data is used. It should be the last column not the 4th column. Newsham 17:53, 7 March 2007 (UTC)

Retrieved from "http://haskell.org/haskellwiki/Programming_performance/Magnus_Haskell"

This page has been accessed 545 times. This page was last modified 17:53, 7 March 2007. Recent content is available under a simple permissive license.