在F#中实现队列类型

时间:2015-11-01 16:19:13

标签: types f# queue

我正在尝试在F#中实现一个队列到目前为止这是我所拥有的,但我认为它的行为更像是一个堆栈:

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之外,这些操作工作正常,我想这样做,所以它会在队列后面而不是前面添加一个新元素。

2 个答案:

答案 0 :(得分:12)

功能队列的规范方法是有两个列表,这些列表导致摊销 O(1)访问:

type queue<'a> =
    | Queue of 'a list * 'a list

let empty = Queue([], [])

let enqueue q e = 
    match q with
    | Queue(fs, bs) -> Queue(e :: fs, bs)

let dequeue q = 
    match q with
    | Queue([], []) -> failwith "Empty queue!"
    | Queue(fs, b :: bs) -> b, Queue(fs, bs)
    | Queue(fs, []) -> 
        let bs = List.rev fs
        bs.Head, Queue([], bs.Tail)

答案 1 :(得分:4)

目前你把它放在前面;如果你想在队列的最后排队,你必须一直前进到那个目的,然后把你的价值:

let rec enque m = function
  NL          -> Que (m, NL)
| Que (x, xs) -> Que (x, enque m xs) // Note : not tail-rec