Created
January 18, 2015 04:48
-
-
Save alphaKAI/2cd58a66ebb10d0bf532 to your computer and use it in GitHub Desktop.
RangeよくわからないからInputRange使ってMapみたいなの作ろうとした結果・・・
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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