Embed queue type in F #

I am trying to implement a queue in F # so far this is what I have, but I think it looks 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);;

Operations work fine, except for enque, I want to make it add a new element to the back of the queue, not the front.

+4
source share
2 answers

You are currently putting it in front; if you want to queue at the end of the queue, you need to go all the way to the end, and then add your value:

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

The canonical approach for functional queues has two lists, which leads to depreciation of 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)
+10
source

Source: https://habr.com/ru/post/1614054/


All Articles