如何实现Haskell函数profit_report生成股票损益报表?
实现Haskell的损益报表函数
profit_report 首先我们需要明确Transaction的类型结构,根据给定的测试日志,定义类型别名:
type Transaction = (Char, Int, Int, String, Int) -- 字段依次为:交易类型('B'代表买入,'S'代表卖出)、交易股数、每股价格、股票名称、交易日期
核心逻辑:计算单只股票的盈亏
对于单只股票,买入交易是资金流出(记为负数),卖出交易是资金流入(记为正数),遍历所有该股票的交易并累加即可得到总盈亏:
calculateProfit :: String -> [Transaction] -> Int calculateProfit targetStock = sum . map calculateSingleTx where calculateSingleTx ('B', shares, price, stock, _) | stock == targetStock = - shares * price calculateSingleTx ('S', shares, price, stock, _) | stock == targetStock = shares * price calculateSingleTx _ = 0 -- 忽略无关交易或未知类型
生成格式化报表
按照输入的股票列表顺序,为每只股票生成STOCK: PROFIT格式的行,最后用换行符拼接所有行:
profit_report :: [String] -> [Transaction] -> String profit_report stockList txLog = unlines $ map formatStockEntry stockList where formatStockEntry stock = stock ++ ": " ++ show (calculateProfit stock txLog)
测试验证
使用给定的测试日志验证功能:
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) ] -- 在GHCi中执行: -- ghci> putStr (profit_report ["VTI", "ONEQ", "IWRD"] test_log) -- 输出结果: -- VTI: 14450 -- ONEQ: -800 -- IWRD: -1900
内容的提问来源于stack exchange,提问作者Stabba_thehut
相关产品推荐
相关产品推荐

