Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a queue type in F#

Tags:

types

queue

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);;

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.

like image 685
coder4lyf Avatar asked Nov 01 '15 16:11

coder4lyf


1 Answers

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)
like image 132
CaringDev Avatar answered Oct 06 '22 20:10

CaringDev