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);;
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.
The canonical approach for functional queues is having two lists, which leads to amortized O(1) access:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With