給定兩個數字串列,例如[1, 2, 0] = 120和[1,0,1] = 101,我的函式sub應該回傳該串列,[1, 9] = 19但該函式正在回傳[2, -1]。我如何解決這個攜帶問題?當沒有進位并且只接收正數時,它作業正常。這是我的代碼:
sub_Carry :: Integer -> [Integer] -> [Integer] -> [Integer]
sub_Carry c x []
| c == 0 = x
| otherwise = sub_Carry 0 [c] x
sub_Carry c [] x
| c == 0 = x
| otherwise = sub_Carry 0 x [c]
sub_Carry c (x : xs) (y : ys) = (x - y) : sub_Carry c xs ys
sub :: [Integer] -> [Integer] -> [Integer]
sub op1 op2
| to_Integer(op1) == to_Integer(op2) = [0]
| to_Integer(op1) > to_Integer(op2) = drop_Zeros (reverse (sub_Carry 0 (reverse op1) (reverse op2)))
| otherwise = [-1] drop_Zeros (reverse (sub_Carry 0 (reverse op1) (reverse op2)))
其他注意事項:
- 我有其他實用程式函式,例如
to_Integer將串列轉換為其對應的整數,drop_Zeros洗掉串列右側的零 ([0, 1, 0] = [1, 0]) - 在結果為負數的情況下,它應該回傳以 -1 開頭的串列 (
[1, 0, 0] - [1, 0, 1] = [-1, 1])
uj5u.com熱心網友回復:
我注意到你沒有使用引數c進行攜帶。它是練習的中心點。還需要解決引數串列y早于 結束的情況x。我的程式僅適用于積極的結果。所以我也修改了函式sub,當op1 < op2. 現在應該總是有一個積極的結果,然后你使用常數 -1 否定它。
sub_Carry :: Integer -> [Integer] -> [Integer] -> [Integer]
sub_Carry 0 [] [] = []
sub_Carry c x [] = sub_Carry c x [0]
sub_Carry c (x : xs) (y : ys)
| (x - y - c) < 0 = (10 x - y - c) : sub_Carry 1 xs ys
| otherwise = (x - y - c ) : sub_Carry 0 xs ys
sub :: [Integer] -> [Integer] -> [Integer]
sub op1 op2
| to_Integer(op1) == to_Integer(op2) = [0]
| to_Integer(op1) > to_Integer(op2) = drop_Zeros (reverse (sub_Carry 0 (reverse op1) (reverse op2)))
| otherwise = [-1] drop_Zeros (reverse (sub_Carry 0 (reverse op2) (reverse op1)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370605.html
標籤:哈斯克尔
