我正在嘗試創建一個函式
update_money :: Transaction -> Int -> Int
它需要一筆交易和您當前擁有的金額,并回傳您在交易后擁有的金額。因此,如果交易買入一只股票,你擁有的資金量就會減少,而如果交易賣出一只股票,你擁有的資金量就會增加。例如:
ghci> update_money ('B', 1, 10, "VTI", 5) 100
90
ghci> update_money ('S', 2, 10, "VTI", 5) 100
120
這是已提供的資料:
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)]
這是我對這個問題的嘗試:
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
但是,當在同一行上說明操作和(顯示單位)時,我得到了型別轉換,所以我不確定如何處理這個問題。
uj5u.com熱心網友回復:
我想我在 Haskell 中(以及在 Python 中)處理這個問題的方式是這樣的:
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
]
在 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)]
uj5u.com熱心網友回復:
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
在我的電腦上輸出。它運作良好。
Registering library for app2-0.1.0.0..
120
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536680.html
標籤:哈斯克尔
上一篇:如何訪問中間件中的回應狀態?
