Difference between revisions of "Programming performance/Magnus Haskell"

From HaskellWiki
Jump to navigation Jump to search
 
(mention minor bugs)
 
(One intermediate revision by one other user not shown)
Line 2: Line 2:
 
* '''Skill''': Intermediate. I'm self taught in Haskell and use it as a hobbyist but haven't used it much for serious work.
 
* '''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.
 
* '''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.
+
* '''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. A while after submitting I noticed I used the wrong data column. It should say column 4, not 3 in closingPrice.
   
 
== Code ==
 
== Code ==
Line 39: Line 39:
 
print result
 
print result
 
</haskell>
 
</haskell>
  +
  +
'''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. [[User:Newsham|Newsham]] 17:53, 7 March 2007 (UTC)

Latest revision as of 17:53, 7 March 2007

  • 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. A while after submitting I noticed I used the wrong data column. It should say column 4, not 3 in closingPrice.

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)