-1

I want to use a method like this one:

public void A(Action<Action<string>> x)
{
    for (int i = 0; i < 10; i++)
    {
        x.Invoke(data => {
             Console.WriteLine($"{data} --- {i}");
        });
    }
}

The idea here is that the user (of this method) will input another method which can generate a string from a data source of preference.
Let's say I want to provide the user with some built-in solutions as static methods:

public void B(string fileName, Action<string> y)
{
     // process fileName
     string data = C(fileName);
     // invoke inner action
     y.Invoke(data);
}

The use case would be:

A(B("/home/user1"));

The problem with this is B still needs another argument for fileName
How do I do that?

mitiko
  • 751
  • 1
  • 8
  • 20

1 Answers1

0

I figured that out as I was typing it...
What I really need to use is a Func<T>, not Action<Action<T>>.
Example:

public void A(Func<string> x)
{
    for (int i = 0; i < 10; i++)
    {
        var data = x.Invoke();
        Console.WriteLine($"{data} --- {i}");
    }
}

public string B(string fileName)
{
     // process fileName
     string data = C(fileName);
     return data;
}

public void Main()
{
    A(B("home/user1"));
}

I couldn't have just passed a string to A, generated by B like:

public void A(string data)

Because this doesn't allow for a change in data source in B (B could change the source based on another parameters - for example if B chose a random file with prefix fileName)

EDIT: This still wouldn't work! the problem is that by invoking B we are surely not passing B as an argument, but rather B's return type.
In my case the change in B's input source is irrelevant and an appropriate solution is to change B to:

public IEnumerable<string> B(string fileName)
{
    foreach (var line in File.ReadAllLines("fileName"))
    {
         yield return line;
    }
}
mitiko
  • 751
  • 1
  • 8
  • 20
  • This does not seem to answer the question - you've started with method-that-returns-method but changed it to something else... Question seem to be about proper currying... – Alexei Levenkov May 19 '19 at 19:13
  • Yes, I realized the given example didn't match my actual use case. This is for a NN btw. – mitiko May 19 '19 at 19:16
  • @AlexeiLevenkov Is that what you'd do? https://gist.github.com/Mitiko/c1f361affeb9ac9b4698dbb04b3a8611 – mitiko May 19 '19 at 19:25
  • 1
    Probably not... It is unclear what you want to achieve... but frequently when people go such length the goal is to do lazy evaluation - so I would not let caller invoke any functions in advance (unlike your `B("home/user1")` but make them do partial application as shown in the duplicate I pick - `A(Apply(B, fileName))` ) – Alexei Levenkov May 19 '19 at 19:32