1 /*
2  * Kiss - A refined core library for D programming language.
3  *
4  * Copyright (C) 2015-2018  Shanghai Putao Technology Co., Ltd
5  *
6  * Developer: HuntLabs.cn
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11  
12 module kiss.util.functional;
13 
14 public import std.functional;
15 public import std.traits;
16 import std.typecons;
17 import std.typetuple;
18 
19 pragma(inline) auto bind(T, Args...)(T fun, Args args) if (isCallable!(T))
20 {
21     alias FUNTYPE = Parameters!(fun);
22     static if (is(Args == void))
23     {
24         static if (isDelegate!T)
25             return fun;
26         else
27             return toDelegate(fun);
28     }
29     else static if (FUNTYPE.length > args.length)
30     {
31         alias DTYPE = FUNTYPE[args.length .. $];
32         return delegate(DTYPE ars) {
33             TypeTuple!(FUNTYPE) value;
34             value[0 .. args.length] = args[];
35             value[args.length .. $] = ars[];
36             return fun(value);
37         };
38     }
39     else
40     {
41         return delegate() { return fun(args); };
42     }
43 }
44 
45 unittest
46 {
47 
48     import std.stdio;
49     import core.thread;
50 
51     class AA
52     {
53         void show(int i)
54         {
55             writeln("i = ", i); // the value is not(0,1,2,3), it all is 2.
56         }
57 
58         void show(int i, int b)
59         {
60             b += i * 10;
61             writeln("b = ", b); // the value is not(0,1,2,3), it all is 2.
62         }
63 
64         void aa()
65         {
66             writeln("aaaaaaaa ");
67         }
68 
69         void dshow(int i, string str, double t)
70         {
71             writeln("i = ", i, "   str = ", str, "   t = ", t);
72         }
73     }
74 
75     void listRun(int i)
76     {
77         writeln("i = ", i);
78     }
79 
80     void listRun2(int i, int b)
81     {
82         writeln("i = ", i, "  b = ", b);
83     }
84 
85     void list()
86     {
87         writeln("bbbbbbbbbbbb");
88     }
89 
90     void dooo(Thread[] t1, Thread[] t2, AA a)
91     {
92         foreach (i; 0 .. 4)
93         {
94             auto th = new Thread(bind!(void delegate(int, int))(&a.show, i, i));
95             t1[i] = th;
96             auto th2 = new Thread(bind(&listRun, (i + 10)));
97             t2[i] = th2;
98         }
99     }
100 
101     //  void main()
102     {
103         auto tdel = bind(&listRun);
104         tdel(9);
105         bind(&listRun2, 4)(5);
106         bind(&listRun2, 40, 50)();
107 
108         AA a = new AA();
109         bind(&a.dshow, 5, "hahah")(20.05);
110 
111         Thread[4] _thread;
112         Thread[4] _thread2;
113         // AA a = new AA();
114 
115         dooo(_thread, _thread2, a);
116 
117         foreach (i; 0 .. 4)
118         {
119             _thread[i].start();
120         }
121 
122         foreach (i; 0 .. 4)
123         {
124             _thread2[i].start();
125         }
126 
127     }
128 }