如何在Haskell中编写Deque数据类型

时间:2011-04-25 03:00:00

标签: haskell types implementation deque

如何在Haskell中编写一个双端队列(“deque”)。数据结构应该具有emptyDeque,front,back,removeFront,removeBack,addFront,addBack和isEmpty等函数,然后在 - >之间显示双端队列。和< - 。

这对于队列来说是相同的:

module Queues (Queue, emptyQueue, front, remove, add, isEmpty)
   newtype Queue a = Queue [a]
   emptyQueue = Queue []
   front  (Queue (x:xs)) = x
   front (Queue []) = error("No front of empty queue")
   add (Queue xs) x = Queue (xs ++ [x])
   remove (Queue (x:xs)) = Queue xs
   remove (Queue []) = error("Nothing on queue to remove")
   isEmpty (Queue []) = True
   isEmpty (Queue (x:xs)) = False
   showElems [] = ""
   showElems (x:xs) = " " ++ (Prelude.show x) ++ (showElems xs)
   showQueue (Queue a) = "<" ++ (showElems a) ++ " >"
   instance (Show a) => Show (Queue a) where show = showQueue

我想出来是不是正确的?

module Deques (Deque, emptyDeque, front, back, removeFront, removeBack , addFront, addBack, isEmpty)
newtype Deque a = Deque [a]
emptyQueue = Queue []
reverses (x:xs) = (reverses xs) ++ [x]
front (Deque (x:xs)) = x
front (Deque []) = error("No front of empty Deque")
back (Deque a) = front(reverse(a))
back (Deque []) = error("No back of empty Deque")
addBack (Deque xs) x = Deque (xs ++ [x])
addFront (Deque xs) x = Deque ([x] ++ xs)
removeFront (Deque (x:xs)) = Deque xs
removeFront (Deque []) = error("Nothing on Deque to remove")
removeBack (Deque a) = reverses(removeFront(reverses(a))
                 `

2 个答案:

答案 0 :(得分:6)

使用列表来实现Deque效率不高,但它可以工作。几点说明

除了键入错误之外,您似乎正在以其他语言的风格编写函数应用程序

front(reverse(a))

在Haskell中,parens只是用于分组。写这行的Haskelly方式就越多

front (reverse a)

甚至

front $ reverse a

另一个注意事项:在Haskell

中添加一些东西到列表的前面是非常典型的
[x] ++ xs -- The weird way
x : xs -- The canonical way

但是添加到列表的后面是很丑陋的。

xs ++ [x] -- No better way for normal lists. This is inefficient

你有一个相当不错的开始,但你应该尝试熟悉Haskell独特的范例和风格。 Learn You a Haskell的前几章做得很好。

答案 1 :(得分:1)

其实这里我的Final Deque实现工作正常

module Deques (Deque, emptyDeque, front, back, removeFront, removeBack, addFront, addBack, isEmpty) where

    newtype Deque a = Deque [a]

    backwards (Deque []) = Deque []

    backwards (Deque a) = Deque( reverse a )

    emptyDeque = Deque []

    front (Deque (x:xs)) = x
    front (Deque []) = error("No front of empty Deque")

    back (Deque a) = front( backwards (Deque a))
    back (Deque []) = error("No back of empty Deque")

    addBack (Deque xs) x = Deque (xs ++ [x])
    addFront (Deque xs) x = Deque (x : xs)

    removeFront (Deque (x:xs)) = Deque xs
    removeFront (Deque []) = error("Nothing on Deque to remove")

    removeBack (Deque a) = backwards( removeFront( backwards (Deque a) ))
    removeBack (Deque []) = error("Nothing on Deque to remove")

    isEmpty (Deque []) = True
    isEmpty (Deque (x:xs)) = False

    showElems [] = ""
    showElems (x:xs) = " " ++ (Prelude.show x) ++ (showElems xs)
    showDeque (Deque a) = "<" ++ (showElems a) ++ " >"

    instance (Show a) => Show (Deque a) where show = showDeque