Created
March 16, 2015 16:03
-
-
Save alphaKAI/01271104d898a117d97b to your computer and use it in GitHub Desktop.
D言語でカリー化を用いて等差数列と等比数列書いてみた例(適当な例)
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.stdio; | |
| template curry(alias func){ | |
| import std.algorithm, std.conv, std.range, std.traits; | |
| alias argsintuple = ParameterTypeTuple!func; | |
| immutable lambdaStr = (lamArgs => | |
| (temp){ | |
| foreach(i, e; argsintuple) | |
| temp ~= "(" ~ e.stringof ~ " " ~ lamArgs[i] ~ ") => "; | |
| return temp ~ "func(" ~ lamArgs.join(", ") ~ ")"; | |
| }("") | |
| )(argsintuple.length.iota.map!(i => "arg" ~ i.to!string)); | |
| enum curry = mixin(lambdaStr); | |
| } | |
| int ap(int a, int d, int n){ | |
| return a + d * (n - 1); | |
| } | |
| int sumAp(int n, int delegate(int) f){ | |
| return sumAp(n, f, 1); | |
| } | |
| int sumAp(int n, int delegate(int) f, int a){ | |
| return n * (f(a) + f(n)) / 2; | |
| } | |
| int gp(int a, int r, int n){ | |
| return a * r ^^ (n - 1); | |
| } | |
| int sumGp(int r, int n, int delegate(int) f){ | |
| return r == 1 ? n * f(1) : (f(1) * (r^^n - 1)) / (r - 1); | |
| } | |
| void main(){ | |
| auto apf = curry!ap; | |
| auto apg = apf(1)(4); | |
| foreach(i; 1..5) | |
| writeln(apg(i)); | |
| writeln(sumAp(4, apg)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment