2017-08-06 7 views
1

文字列が与えられたときに作成されたすべての関数を渡し、変更された文字列を生成する一連の関数を作成したいと考えています。例: コレクションの関数を生成して結合する

string[] arr = {"po", "ro", "mo", "do"}; 

var modify = "pomodoroX"; 
foreach (var token in arr) 
{ 
    modify = modify.Replace(token, ""); 
} 
Console.WriteLine(modify); // Output: X 

これは、問題を解決するが、私は機能性溶液中で興味を持っています:

Console.WriteLine(
    arr.Select<string, Func<string, string>>(val => (s1 => s1.Replace(val, string.Empty))) 
     .Aggregate((fn1, fn2) => fn1 += fn2) 
     .Invoke("pomodoroX") 
); 
    // Output: pomoroX -> Only last element applied because: 
    // the functions are not getting combined. 

だから、基本的には、配列「ARR」を取ると、各弦のため、その文字列を削除する機能を作成します。 現在のソリューションに欠陥があり、最後の関数だけが適用されます。これを代理人に変換して、+=演算子と組み合わせることはできません。

さらに機能的なソリューションがありますか?

答えて

3

さて、あなたSelectはあなたの文字列に取る代表団のコレクションを与え、変更された文字列を生成するので、あなたは途中でそこにいます。必要なのは、Aggregate経由チェーン一緒にこれらにある - そして次のようにあなたがそれを行う方法は、次のとおりです。

string[] arr = { "po", "ro", "mo", "do" }; 

string result = arr 
    // Produce our collection of delegates which take in the string, 
    // apply the appropriate modification and return the result. 
    .Select<string, Func<string, string>>(val => s1 => s1.Replace(val, string.Empty)) 
    // Chain the delegates together so that the first one is invoked 
    // on the input, and each subsequent one - on the result of 
    // the invocation of the previous delegate in the chain. 
    // fn1 and fn2 are both Func<string, string>. 
    .Aggregate((fn1, fn2) => s => fn2(fn1(s))) 
    .Invoke("pomodoroX"); 

Console.WriteLine(result); // Prints "X". 
+0

おかげでたくさんの友人! Soo関数の構成は、fn(fn2(param))と同様に行われます。 – rinormaloku

+0

@rinormaloku、それはまさに正しいことです。 –

1

私は本当に「機能」としてカウントされますかわかりません。私はあなたがフロー制御構造を使用したくないと仮定します。

これは簡単です。そう思わないですか?

string[] arr = {"po", "ro", "mo", "do"}; 
arr.Aggregate("pomodoroX", (x, y) => x.Replace(y, "")) 
+0

クールで、ちょうどC#を学び、とても強力です。 (まだJavaの方法を考えています)。 機能的には、常に外部から変更している変数がないことを意味します。このようにして、それぞれが変更を行い、パラメータとして他の関数に渡す一連の関数に渡しています。 – rinormaloku

関連する問題