在 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屋!
查看全文