在F#中实现队列类型 [英] Implement a queue type in F#
本文介绍了在F#中实现队列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我正在尝试在F#中实现队列,但是我认为它的行为更像是堆栈:
I'm trying to implement a queue in F# so far this is what I have but I think it's acting more like a stack:
type 'a queue = NL| Que of 'a * 'a queue;;
let enque m = function
|NL -> Que(m, NL)
|Que(x, xs) -> Que(m, Que(x, xs));;
let rec peek = function
|NL -> failwith "queue is empty"
|Que(x, xs) -> x;;
let rec deque = function
|NL -> failwith "queue is empty"
|Que(x, xs) -> xs;;
let rec build = function
| [] -> NL
| x::xs -> enque x (build xs);;
除了enque之外,其他所有操作都工作正常,我想这样做,以便将新元素添加到队列的后面而不是前面.
The operations are working fine except for enque, I want to make it so it adds a new element to the back of the queue instead of the front.
推荐答案
当前您将其放在最前面;如果要排队进入队列的末尾,则必须一直进行到该队列的末尾,然后输入值:
Currently you are putting it at the front ; if you want to enqueue at the end of the queue you have to progress all the way to that end and then put your value :
let rec enque m = function
NL -> Que (m, NL)
| Que (x, xs) -> Que (x, enque m xs) // Note : not tail-rec
这篇关于在F#中实现队列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文