[Haskell] Queue

1. 列表表示

module Queue(Queue,emptyQueue,queueEmpty,enqueue,dequeue,front) where 

newtype Queue a = Q [a]
    deriving Show 

emptyQueue :: Queue a 
emptyQueue = Q []

queueEmpty :: Queue a -> Bool
queueEmpty (Q []) = True 
queueEmpty (Q _) = False

enqueue :: a -> Queue a -> Queue a 
enqueue x (Q q) = Q (q ++ [x])

dequeue :: Queue a -> Queue a 
dequeue (Q (_:xs)) = Q xs 
dequeue (Q []) = error "dequeue: empty queue"

front :: Queue a -> a 
front (Q (x:_)) = x
front (Q []) = error "front: empty queue"

2. 使用两个列表

module Queue(Queue,emptyQueue,queueEmpty,enqueue,dequeue,front) where 

newtype Queue a = Q ([a], [a])

emptyQueue :: Queue a 
emptyQueue = Q ([], [])

queueEmpty :: Queue a -> Bool
queueEmpty (Q ([], [])) = True 
queueEmpty _ = False

enqueue :: a -> Queue a -> Queue a 
enqueue x (Q ([], [])) = Q ([x], [])
enqueue y (Q (xs, ys)) = Q (xs, y:ys)

dequeue :: Queue a -> Queue a 
dequeue (Q ([], [])) = error "dequeue: empty queue"
dequeue (Q ([], ys)) = Q (tail $ reverse ys, [])
dequeue (Q (x:xs, ys)) = Q (xs, ys)

front :: Queue a -> a 
front (Q ([], [])) = error "front: empty queue"
front (Q ([], ys)) = last ys
front (Q (x:xs, ys)) = x

instance (Show a) => Show (Queue a) where 
    showsPrec p (Q (front, rear)) str = 
        showString "Q " (showList (front ++ reverse rear) str)

参考

Algorithms: A Functional Programming Approach

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 人的一生有很多个感觉好极了 也会经历很多感觉糟透了 不过其实,这些都没什么,不用看得很重 很多年以后,当你回忆过去...
    孔庆芬阅读 4,852评论 0 2
  • 喏~你们要的“仙女”神器 牙白整个人都自信了,也爱笑了。每天被人夸也是美美的,不仅白还发亮 做了一段时间小白鼠,终...
    瑶三岁_7481阅读 1,592评论 0 0
  • 在经历了直销模式和电商的接连打击之后,中国的零售行业该何去何从呢? 这里首先对直销和电商进行一点介绍: 直销:顾名...
    家和万事亨阅读 1,807评论 0 1
  • 很庆幸心理学会有这样的沙龙,帮助更多的人去成长学习。 不同的人分享关于情感、婚姻的内容,让我感慨于遇到...
    雨山Joan阅读 1,358评论 0 0