Group adjacent values The task is to group adjacent values from collection and output it as a new aggregated collection.

Consider we have following input:


Sequence
Number      Value
========    =====
1           9
2           9
3           15
4           15
5           15
6           30
7           9


The aim is to enumerate over Sequence Numbers and check if the next element has the same value. If yes, values are aggregated and so, desired output is as following:


Sequence    Sequence
Number      Number
From        To          Value
========    ========    =====
1           2           9
3           5           15
6           6           30
7           7           9


Build a code with following assumptions:


Sequence Numbers are already ordered in input table.
There can be gaps in Sequence Numbers. If input contains gaps, output should contain gaps too. For example input 1 99\n2 99\n4 99\n6 99, output will be 1 2 99\n4 4 99\n6 6 99.
Assume Value is type of integer.
It can be a full program or just a function.
This cruft (Sequence Sequence\n ... ======== ======== =====\n) is not a part of output. Output format is not defined; there should be a delimeter between values and between rows, so anyone can distinguish values and rows.


It's an extend of my StackOverflow question: https://stackoverflow.com/questions/14879197/linq-query-data-aggregation.
K, 43 38

{d:(x;0N,x;y)@\:&amp;~~':y;d[1]:(1_d 1),*|x;+d}

{a::*|x;+@[(x;{x,a};y)@\:&amp;~~':y;1;1_]}


.

k){a::*|x;+@[(x;{x,a};y)@\:&amp;~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9 
3 5 15
6 6 30
7 7 9


Explanation

The function takes two vectors, x and y, as input

a::*|x takes the last value of x and assigns it to a.

&amp;~~':y returns a list of indices where the y vector changes:

k){&amp;~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
0 2 5 6


(x;{x,a};y) creates a three element list containing 

1) the x vector,

2) the function {x,a} which takes an input variable x(not to be confused with the x vector which was input into the original function) and appends a, and 

3) the y vector

(x;{x,a};y)@\:&amp;~~':y takes this three element list and applies the indices to each element
so that we return the x vector at those indices, the indices with a appended, and the y vector at those indices

k){b::*|x;(x;{x,b};y)@\:&amp;~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3 6 7
0 2 5 6 7
9 15 30 9


@[(x;{x,a};y)@\:&amp;~~':y;1;1_] takes the matrix we've created and drops the first element of the second row.

k){b::*|x;@[(x;{x,b};y)@\:&amp;~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3  6  7
2 5  6  7
9 15 30 9


+ then transposes the result

k){b::*|x;+@[(x;{x,b};y)@\:&amp;~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9 
3 5 15
6 6 30
7 7 9