i have a question regarding this Haskell code:
module Queue (Queue, emptyQueue, queueEmpty, enqueue, dequeue, front) where
newtype Queue a = MakeQ([a])
emptyQueue :: Queue a
emptyQueue = MakeQ([])
queueEmpty :: Queue a -> Bool
queueEmpty (MakeQ(q)) = null q
enqueue :: a -> Queue a -> Queue a
enqueue x (MakeQ(q)) = MakeQ(q ++ [x])
dequeue :: Queue a -> Queue a
dequeue (MakeQ(x:q)) = MakeQ(q)
front :: Queue a -> a
front (MakeQ(x:q)) = x
I know how a queue generally works and what each of the operations mainly does. My first problem is that i don’t know how to use the operations in hugs. How do i create a empty queue or put an element in it after i created it? I tried several commands but all of them resulted in error messages, i.e. Make([]), emptyQueue [] … I know that those commands are very naive, but i am absolutly not familiar with Haskell and need it only for 2 weeks or so.
Second question is regarding the “MakeQ” itself. This is just a declaration for a name for our operation, correct? Or is it a static Haskell command? Imo it could be also “QQQ” or whatever. I can’t really test whether this would crash the programm or not because i don’t know how to use this module.
Even if my question seem kind of stupid, i would be really happy if someone could give me an explanation or hints…
emptyQueueby itself is an empty queue; you don’t have to pass any parameters to it.MakeQis just an arbitrary name, you’re right; it could be anything (as long as you changed all the other uses of it). In this case, it’s the constructor forQueue: ifxsis a list ofavalues (i.e. has type[a]), thenMakeQ xsis aQueue a. However, the module does not exportMakeQ, so you can’t use it from outside — it’s used as part of the implementation, and hidden to maintain an abstraction; it could easily be rewritten in terms of another, non-list structure without breaking any code that uses the module.Operations on the queue are done, not by updating an existing queue in-place, but by transforming a queue into new queues. For instance, if
ais anInt, andqis aQueue Int, thenenqueue a qis anotherQueue Intwithaadded to the back. Similarly, ifqis aQueue Int, thendequeue qis anotherQueue Intwithout the front element, andfront qis the front element itself (anInt).Also, note that Hugs is not maintained any more; you should consider installing the Haskell Platform, which is based on the GHC compiler. It contains an “interpreter” program just like Hugs, so it’s not just a standard compiler.
Here’s an example of how this queue module could be used from an interactive prompt:
If you’re trying to maintain a queue throughout the execution of a program, then you probably want to use the state monad, which is a lot less scary than it sounds. 🙂 I would recommend reading Learn You a Haskell, which is an excellent Haskell tutorial covering, among many other things, the state monad.