Haskell - 删除功能不起作用

时间:2015-11-29 07:50:00

标签: haskell

我正在研究一个有界的队列。有界队列由两部分组成,即队列本身(数字队列)及其容量。

type Queue = [Int]
type Capacity = Int
data BoundedQueue = BoundedQueue Queue Capacity deriving (Show)

BoundedQueue的例子:

bq1 :: BoundedQueue
bq1 = BoundedQueue [1,2,3,4,5] 5
bq2 :: BoundedQueue
bq2 = BoundedQueue [] 5

我想创建一个删除功能。该功能是从指定的有界队列中删除一个数字。

delete :: Int -> BoundedQueue -> BoundedQueue
delete int (BoundedQueue [] ys) = error "Not found"
delete int (BoundedQueue (x:xs) ys) | int == x = (BoundedQueue xs ys)
                                    | otherwise = delete int (BoundedQueue xs ys)

但删除功能无法正常工作。它还会删除已删除项目之前的所有内容。这是一个例子:

*Main> delete 2 bq1
BoundedQueue [3,4,5] 5

什么时候应该

BoundedQueue [1,3,4,5] 5

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

当您在delete中遍历队列时,您将删除所有项目,直到找到所需的项目。您需要重新插入要保留的元素:

delete :: Int -> BoundedQueue -> BoundedQueue
delete int (BoundedQueue [] c) = error "Not found"
delete int (BoundedQueue (x:xs) c) 
  | int == x  = (BoundedQueue xs c)                                  
  | otherwise = 
    let BoundedQueue xs' _ = delete int (BoundedQueue xs c)
    in BoundedQueue (x:xs') c 
 --                  ^-- keep the current element as well

按预期工作:

λ> delete 2 bq1
BoundedQueue [1,3,4,5] 5

您可能还想删除error来电并让类型说明delete是部分操作:

delete :: Int -> BoundedQueue -> Maybe BoundedQueue
delete int (BoundedQueue [] c) = Nothing
delete int (BoundedQueue (x:xs) c)
  | int == x  = Just (BoundedQueue xs c)
  | otherwise = do
    BoundedQueue xs' _ <- delete int (BoundedQueue xs c)
    Just (BoundedQueue (x:xs') c)