Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Created January 18, 2015 04:48
Show Gist options
  • Select an option

  • Save alphaKAI/2cd58a66ebb10d0bf532 to your computer and use it in GitHub Desktop.

Select an option

Save alphaKAI/2cd58a66ebb10d0bf532 to your computer and use it in GitHub Desktop.
RangeよくわからないからInputRange使ってMapみたいなの作ろうとした結果・・・
import std.algorithm,
std.stdio,
std.conv;
void main(){
int fact(int n){
return n == 1 ? 1 : n * fact(n - 1);
}
auto mapper = Maper!(int delegate(int), int)(&fact, [1, 2, 3, 4, 5]);
foreach(v; mapper)
v.call.writeln;
mapper.map.writeln;
}
struct Maper(T, U){
struct mapItem{
T fanc;
U arg;
auto call(){
return fanc(arg);
}
}
private mapItem[] items;
this(T t, U[] u){
foreach(eu; u){
mapItem tmp;
tmp.fanc = t;
tmp.arg = eu;
items ~= tmp;
}
}
U[] map(){
U[] results;
foreach(e; items){
results ~= e.call;
}
return results;
}
Range opSlice(){
return Range(this);
}
struct Range{
Maper outer;
int frontCursor;
this(Maper o){
outer = o;
}
@property bool empty(){
return frontCursor >= outer.items.length;
}
@property mapItem front(){
return outer.items[frontCursor];
}
void popFront(){
++frontCursor;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment