gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:11:03 25 4
gpt4 key购买 nike

如何在 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))
`

最佳答案

使用列表来实现双端队列效率不是很高,但它可以工作。一些注意事项

抛开类型错误不谈,您似乎正在以其他语言的风格编写函数应用程序

front(reverse(a))

在 Haskell 中,括号仅用于分组。编写该行的更多 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的前几章做好这件事。

关于haskell - 如何在 Haskell 中编写 Deque 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com