目標是構建一個程式,以人類可讀的格式報告特定股票的交易。例如,對于我們的測驗資料集,股票 VTI 上的交易將列印為:
Bought 100 units of VTI for 1104 pounds each on day 1
Bought 50 units of VTI for 1223 pounds each on day 5
Sold 150 units of VTI for 1240 pounds each on day 9
這是測驗交易代碼:
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)
]
為此,我認為最好將每個部分分成幾片,最后可以將它們連接起來。
--Converting transaction to string
transaction_to_string :: Transaction -> String
transaction_to_string (action: units: stocks: price: day) =
let display = action "Bought"
slice1 = units "of"
slice2 = stocks "for"
slice3 = price "on day"
slice4 = day
in
slice1 slice2 slice3 slice4
我收到的錯誤是這個。它給出了型別錯誤,但由于頂部使用的型別函式,我不確定原因:
? Couldn't match type ‘[Char]’ with ‘Char’
Expected: [Char]
Actual: [[Char]]
? In the second argument of ‘( )’, namely ‘slice4’
In the second argument of ‘( )’, namely ‘slice3 slice4’
In the second argument of ‘( )’, namely
‘slice2 slice3 slice4’
|
| slice1 slice2 slice3 slice4
uj5u.com熱心網友回復:
第一次嘗試:
transaction_to_string :: Transaction -> String
transaction_to_string (action, units, stocks, price, day) =
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tuple, not list
let display = show action "Bought" -- << convert non-strings using `show`
slice1 = show units "of" -- <<
slice2 = show stocks "for" -- <<
slice3 = price "on day"
slice4 = show day -- <<
in
display slice1 slice2 slice3 slice4
您可以通過以下方式改進:
在正確的地方添加空格
更好地格式化字串:連接的順序似乎有點偏離(測驗一下!)
正確處理
display,也許使用類似的東西:let display | action == 'B' = "Bought" | action == 'S' = "Sold" | otherwise = "Uhh.. what?"
uj5u.com熱心網友回復:
假設Transaction不是型別同義詞,理想情況下您會將其設為Show. 例如,如果我們使用記錄型別。
data Transaction = Transaction {
action :: Char,
units :: Int,
stocks :: String,
price :: Int,
day :: Int
}
instance Show Transaction where
show (Transaction {action=a, units=u, stocks=s, price=p, day=d}) = str
where
a' = case a of
'B' -> "Bought"
'S' -> "Sold"
_ -> "Unknown action"
str = a' " " show u " units of " s
" at $" show p " on day " show d
現在:
Prelude> Transaction {action='B', units=100, stocks="FOO", price=56, day=7}
Bought 100 units of FOO at $56 on day 7
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531104.html
標籤:哈斯克尔
下一篇:Haskell函式的時間復雜度
