C
C#9mo ago
__dil__

❔ Is there a built-in way to map (transform) a tuple?

For example, I'd like to do this (hypothetical code):
bool foo = (val: 1.0, truthiness: true, name: "hello").Map((bar) => { bar.val > 0 && bar.name == "Bob" || bar.truthiness });
bool foo = (val: 1.0, truthiness: true, name: "hello").Map((bar) => { bar.val > 0 && bar.name == "Bob" || bar.truthiness });
instead of that
var bar = (val: 1.0, truthiness: true, name: "hello");
bool foo = bar.val > 0 && bar.name == "Bob" || bar.truthiness;
var bar = (val: 1.0, truthiness: true, name: "hello");
bool foo = bar.val > 0 && bar.name == "Bob" || bar.truthiness;
The reasoning is that it's cumbersome to have to introduce variable names for intermediate computations involving tuples. Being able to transform them directly makes it possible to avoid that.
7 Replies
Thinker
Thinker9mo ago
If I'm understanding correctly, there is no built-in way to do it, but you could have a general-purpose Map extension.
public static TResult Map<TSource, TResult>(this TSource source, Func<TSource, TResult> map) => map(source);
public static TResult Map<TSource, TResult>(this TSource source, Func<TSource, TResult> map) => map(source);
MODiX
MODiX9mo ago
Thinker
REPL Result: Success
static TResult Map<TSource, TResult>(this TSource source, Func<TSource, TResult> map) => map(source);

bool foo = (val: 1.0, truthiness: true, name: "hello").Map((bar) => bar.val > 0 && bar.name == "Bob" || bar.truthiness);
foo
static TResult Map<TSource, TResult>(this TSource source, Func<TSource, TResult> map) => map(source);

bool foo = (val: 1.0, truthiness: true, name: "hello").Map((bar) => bar.val > 0 && bar.name == "Bob" || bar.truthiness);
foo
Result: bool
True
True
Compile: 690.131ms | Execution: 118.999ms | React with ❌ to remove this embed.
Thinker
Thinker9mo ago
I assume what you're looking for is more like F#'s built-in |> operator
__dil__
__dil__9mo ago
I don't know F#, so I can't really comment on that. By "built-in" I merely meant "something part of the standard library".
Thinker
Thinker9mo ago
Yeah no, there isn't
__dil__
__dil__9mo ago
it seems like your solution works just fine though (although it's not built-in) thanks!
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.