1 /*******************************************************************************
2  * Common.d - Functions and structures universal to all of Cookbook.
3  *            Short and common functions beneficial to all and widely applicable.
4  */
5 
6 module cookbook.essential.common;
7 
8 pure T[] append(T)(T[] l, T t){
9   T[] r;
10   r.length = l.length+1;
11   for(int i = 0; i < l.length; i++){
12     r[i] = l[i];
13   }
14   r[l.length] = t;
15   return r;
16 }
17 
18 pure T[] map(alias f, T)(T[] l){
19   T[] r;
20   foreach(i; l) r = append!T(r,f(i));
21   return r;
22 }
23 
24 pure T[] filter(alias pred, T)(T[] list){
25   T[] rlist;
26   foreach(item; list)
27     if(pred(item)) rlist = append!T(rlist,item);
28   return rlist;
29 }
30 
31 pure T[][] zip(T)(T[] list1, T[] list2){
32   if(list1.length == 1 || list2.length == 1)
33     return [[list1[0],list2[0]]];
34   else return [[list1[0],list2[0]]]~zip(list1[1..$],list2[1..$]);
35 }
36 
37 pure int[] range(int start, int end){
38   int[] ret;
39   for(int i = start; i < end; i++){
40     ret = append!int(ret,i);
41   }
42   return ret;
43 }
44 
45 pure int[] positions(T)(T[] list, T item){
46   int[] ret;
47   for(int i = 0; i < list.length; i++){
48     if(list[i] == item)
49       ret = append!int(ret,i);
50   }
51   return ret;
52 }
53 
54 pure int pos(T)(T[] list, T item){
55   return positions!T(list,item).dup[0];
56 }
57 
58 pure int count(T)(T[] list, T item){
59   int count = 0;
60   foreach(ind; list){
61     if(ind == item) count++;
62   }
63   return count;
64 }
65 
66 pure T[] after(T)(T[] data, T item){
67   return data[pos!T(data,item)+1..$];
68 }
69 
70 pure T[] before(T)(T[] data, T item){
71   return data[0..pos!T(data,item)];
72 }