Haskell - delete function doesn't work

I'm working on a bounded queue. The bounded queue consists of two parts, the queue itself (a queue of numbers) and its capacity.

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

Examples of the BoundedQueue:

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

I want to create a delete function. The function is to delete a number from a specified bounded queue.

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)

But the delete function doesn't work properly. It also deletes everything that preceded the deleted item. Here's a example:

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

when it should be

BoundedQueue [1,3,4,5] 5

How to fix this problem?

Answers


When you traverse the queue in delete you remove all items until you find the one you want. You'll need to reinsert the elements that you want to keep:

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

Works as intended:

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

You might also want to remove the error call and make the types say that delete is a partial operation:

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)

Need Your Help

Node express command not found

node.js express

i have used npm install -g express.

Web audio API : perfect looping how to

javascript audio web

When playing file as a loop, there is still an "audio blank" between end and start.