Design by Introspection - Looking for examples

Petar Petar
Tue Jan 15 07:14:22 UTC 2019


On Tuesday, 15 January 2019 at 00:42:37 UTC, Tony A wrote:
> Hi, I just watched the Andrei's talk about Design by 
> Introspection and for what I see this is used in D.
>
> Could anyone point out some good Github examples that I can see 
> this in action and the benefits?
>
> Thanks.

Basically, look for `static if`s in Phobos. A couple of rich 
modules/packages:
https://github.com/dlang/phobos/tree/master/std/algorithm
https://github.com/dlang/phobos/blob/master/std/range/package.d
https://github.com/dlang/phobos/blob/master/std/typecons.d
https://github.com/dlang/phobos/tree/master/std/experimental/allocator
https://github.com/dlang/phobos/blob/master/std/experimental/checkedint.d

In particular, (just from the top of my head) I think that 
`std.range.retro` is nice canonical example:
https://github.com/dlang/phobos/blob/23f600ac78591391f7009beb1367fb97bf65496c/std/range/package.d#L256

* The `retro` function takes a range argument and returns the 
elements of the range in reverse order. For example [1, 2, 3] 
would become [3, 2, 1].

* The main point of all range algorithms in `std.range` is that 
they're lazy, which means that when possible they will attempt to 
process elements one by one, instead of eagerly performing the 
whole algorithm at once. The way this is achieved is by wrapping 
the input in a struct that encapsulates the traversal and allows 
the caller to call the range primitives on the object returned by 
the range algorithm whenever they want.

* So almost all range functions return structs that have somewhat 
different capabilities. For example the range returned by `[1, 2, 
3].map!(x => x * 2)` has random access (you can immediately 
access any element, without needing to evaluate `x => x * 2` for 
any previous element), while `someArray.filter!(x => x % 2) 
doesn't have random access as in general you don't know which 
elements of `someArray` satisfy the `x => x % 2` condition.

So the point of Design by Introspection in the `retro` example is 
that it allows to return a range that best matches the 
capabilities of the argument.


More information about the Digitalmars-d-learn mailing list