Home > Mobile >  Haskell increasing and decreasing value in list
Haskell increasing and decreasing value in list

Time:11-16

I am trying to create a function

update_money :: Transaction -> Int -> Int

that takes a transaction and the current amount of money that you have, and returns the amount of money that you have after the transaction. So if the transaction buys a stock the amount of money you have will decrease, and if the transaction sells a stock the amount of money you have will increase. For example:

ghci> update_money ('B', 1, 10, "VTI", 5) 100
90
ghci> update_money ('S', 2, 10, "VTI", 5) 100
120

This is the data that has been provided:


type Transaction = (Char, Int, Int, String, Int) 
test_log :: [Transaction]    
test_log = [('B', 100, 1104, "VTI", 1),
('B', 200, 36, "ONEQ", 3),
('B', 50, 1223, "VTI", 5),
('S', 150, 1240, "VTI", 9),
('B', 100, 229, "IWRD", 10),
('S', 200, 32, "ONEQ", 11),
('S', 100, 210, "IWRD", 12)]

Here is my attempt at the problem:

update_money :: Transaction -> Int -> Int
update_money x (action, units, price, stocks, day) = 
    let money_type | action == 'B' = show (units - x)
                | action == 'S' = show (units   x)
                | otherwise     = "Incorrect, please input either B for bought or S for sold. " 
    in
        money_type

However, when stating action and (show units) on the same line I am getting a type conversion so am not sure in how I can approach this.

CodePudding user response:

I guess the way I'd approach this in Haskell (and in Python, for that matter) would look like this:

import qualified Data.Map as M

trans lst = M.fromListWith ( )
    [ (stock, (if transaction == 'B' then id else negate) (units * price_per_unit))
    | (transaction, units, price_per_unit, stock, day) <- lst
    ]

Try it in ghci:

> trans [('B', 100, 1104, "VTI", 1), ('B', 200, 36, "ONEQ", 3), ('B', 50, 1223, "VTI", 5), ('S', 150, 1240, "VTI", 9), ('B', 100, 229, "IWRD", 10), ('S', 200, 32, "ONEQ", 11), ('S', 100, 210, "IWRD", 12)]
fromList [("IWRD",1900),("ONEQ",800),("VTI",-14450)]

CodePudding user response:

update_money (action, units, price, stocks, day) sum = 
    let money_type  | action == 'B' = sum - units * price
                    | action == 'S' = sum   units * price
                    | otherwise     = 0
    in
        money_type

main = print $ update_money ('S', 2, 10, "VTI", 5) 100

output in my PC. It works well.

Registering library for app2-0.1.0.0..
120
  • Related