www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - how to remove duplicate code in functional style

reply berni <someone somemail.de> writes:
I've got the following code, which works, but obviously contains 
duplication. Is there a way to move that 
"dissection_available?...:..." to the place, where it should be?

 return dissection_available
     ?solution.dup

              

              .map!(a=>a[0].to!string~"  "~a[1].to!string)
              .join("\n")
              .to!string
     :solution.dup

              .join("\n")
              .to!string;
solution and dissection are of type const(int[][]).
Nov 23 2018
parent Alex <sascha.orlov gmail.com> writes:
On Friday, 23 November 2018 at 14:33:40 UTC, berni wrote:
 I've got the following code, which works, but obviously 
 contains duplication. Is there a way to move that 
 "dissection_available?...:..." to the place, where it should be?

 return dissection_available
     ?solution.dup

              

              .map!(a=>a[0].to!string~"  "~a[1].to!string)
              .join("\n")
              .to!string
     :solution.dup

              .join("\n")
              .to!string;
solution and dissection are of type const(int[][]).
Isn't the standard way of removing duplicate code in functional style to write more small grained functions? like return solution . initialCommonOperation . someAction(dissection, dissection_available) . finalCommonOperation; auto commonInitialCommonOperation(T)(T input) { return } auto someAction(T, A)(T tmp, A dissection, bool dissection_available) { return dissection_available ? tmp.zip(dissection.dup.transposed.map!(a=>a.map! .map!(a=>a[0].to!string~" "~a[1].to!string) : tmp; } auto finalCommonOperation(T)(T tmp) { return tmp.join("\n").to!string; } Don't know, if this compiles... but you get my point ;)
Nov 23 2018