我正在嘗試撰寫 runByte 代碼,它執行一系列指令,并在完成后回傳堆疊頂部的值。如果執行程序中出現錯誤,則回傳 Nothing。我有這個資料型別和功能。
data Bytecode = PUSH Int
| ADD
| SUB
| MULT
| DIV
deriving (Eq, Show)
runBytecode :: [Bytecode] -> Maybe Int
runBytecode [PUSH x] = Just x
runBytecode [PUSH l, PUSH r, ADD] = ( ) <$> (runBytecode [PUSH l]) <*> (runBytecode [PUSH r])
runBytecode [PUSH l, PUSH r, SUB] = (-) <$> (runBytecode [PUSH l]) <*> (runBytecode [PUSH r])
runBytecode [PUSH l, PUSH r, DIV] = (div) <$> (runBytecode [PUSH l]) <*> (runBytecode [PUSH r])
runBytecode [PUSH l, PUSH r, MULT] = (*) <$> (runBytecode [PUSH l]) <*> (runBytecode [PUSH r])
當我嘗試進行單個操作時它可以作業,runBytecode [PUSH 1, PUSH 2, ADD]但是當我嘗試多個操作時,runBytecode [PUSH 1, PUSH 4, PUSH 9, MULT, ADD]我會得到非詳盡的模式,我怎樣才能將我的模式匹配更改為所有這些情況?
uj5u.com熱心網友回復:
您列出的運算式僅適用于僅包含一或三個元素的串列。您應該使用堆疊,以便將專案推入堆疊,然后彈出并推入結果,因此:
runBytecode :: [Bytecode] -> Maybe Int
runBytecode = go []
where go (x:_) [] = Just x
go xs (PUSH x:ys) = go (x:xs) ys
go (x1:x2:xs) (ADD:ys) = go (x1 x2:xs) ys
# ?
go _ _ = Nothing
因此,在這里我們使用 as 模式和: 這將匹配作為第一項的非空串列,但它是具有任意數量剩余元素的串列。(x1:x2:xs)(ADD:ys)ADDxs
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/462833.html
標籤:哈斯克尔
