Reading — step 1 of 5
Learn
~1 min readFunctions and Ranges
Standard C-style function definitions:
int square(int n) {
return n * n;
}
auto add(int a, int b) { // return type inferred
return a + b;
}
Default arguments like Python:
string greet(string name, string greeting = "Hello") {
return greeting ~ ", " ~ name ~ "!";
}
~ is D's string concatenation (+ is reserved for arithmetic; trying it gives a compile error — refreshing).
Lambdas with =>:
auto double_it = (int x) => x * 2;
auto add_them = (int a, int b) => a + b;
Functions are first-class — pass them around:
import std.algorithm : map;
auto squared = [1, 2, 3].map!(x => x * x);
Note !() for compile-time template arguments (the lambda is a type parameter to map).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…