0

I have a datatype of the form :

datatype 'a mlqueue = N | Q of (int * int * 'a) list;

I have to write a dequeue function such that

val dequeue : 'a mlqueue -> 'a * 'a mlqueue*

So if my queue is :

val q = Q [(0,0,3),(1,0,4),(1,1,2),(2,0,5),(2,1,6),(2,2,1)];
- dequeue q;
val it = (4,Q [(1,1,2),(2,0,5),(2,1,6),(2,2,1)]) : int * int mlqueue

Here is my problem:

fun dequeue (Q []) = raise Empty | dequeue (Q((l,p,v)::xs)) = (v, Q xs);

The function in this form won't modify the original queue and when I call dequeue for the second time, it gives the same output as it did for the first time.

Can anyone please help and tell me how to write this function?

Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
na899
  • 163
  • 1
  • 2
  • 9
  • What code have you tried? – ben rudgers Nov 17 '14 at 04:12
  • fun dequeue (Q []) = raise Empty | dequeue (Q((l,p,v)::xs)) = (v, Q xs); – na899 Nov 17 '14 at 04:14
  • "The function in this form won't modify the original queue". Yes, that's how functional programming works, and is exactly as expected. The function is fine - maybe you have a "higher-level" problem that you're trying to solve using it? – molbdnilo Nov 17 '14 at 14:58
  • yeah. I figured out that what I need to do is write the test like this: val q = Q [(0,0,3),(1,0,4),(1,1,2),(2,0,5),(2,1,6),(2,2,1)]; val (x,q) = dequeue q; – na899 Nov 17 '14 at 16:21
  • @na899 It's important to understand that using `val (x,q) = dequeue q`, you create a new value named `q`. The old value does not change (as molbdnilo said, this is a concept of functional programming); e.g. if you had a line like `val w = q` earlier, this `w` would still be the original value before dequeing. – waldrumpus Nov 18 '14 at 09:41

0 Answers0