Challenge Tuples
Nick Treleaven
nick at geany.org
Sat Apr 27 15:32:40 UTC 2024
On Saturday, 27 April 2024 at 11:55:58 UTC, Basile B. wrote:
> Here's [STYX](https://gitlab.com/styx-lang/styx) solution:
>
>
> function sum[T,U](U u): u32
I think you meant `: T`.
> {
> var T result;
> foreach const e in u do
> if echo(is, e, T) do
> result += e;
> else do
> result += sum![T](e);
> return result;
> }
>
> function main(): s32
> {
> assert((1, 2, 3, [1, 3], 5).sum![u32]() == 15);
> return 0;
> }
Mostly equivalent D:
```d
R sum(R = long, T)(T v)
{
R r;
foreach (e; v)
{
static if (is(typeof(e) == int))
r += e;
else
r += sum!R(e);
}
return r;
}
void main()
{
import std;
assert(tuple(1, 2, 3, [1, 3], 5).sum == 15);
}
```
More information about the Digitalmars-d-learn
mailing list