0

I need to write a function that takes function with one parameter as paramemer and return this function as lazy function. This code doesn't work and I have really no idea what this function should return and how I can somehow convert normal function to lazy function.

public static Lazy<int> memo2(Func<int, int> f1) => x => new Lazy<int>(f1(x)); 
  • 2
    What are you actually trying to accomplish? – Nigel Jun 09 '22 at 19:43
  • The constructor for `Lazy` wants _a function that returns an integer_ as its argument but you have provided _an integer_. Perhaps you meant `new Lazy(() => f1(x))` – Wyck Jun 09 '22 at 19:46
  • The `Func` is defining a method that takes a parameter and returns a value. But you want to make that `Lazy`. So is the caller of whatever your Lazy implementation looks like supposed to supply this parameter to the `Func`? If so, your return value will look something like `Func>`, which doesn't really help anything. – Jonesopolis Jun 09 '22 at 19:52
  • 3
    It sounds like you want to implement [memoization](https://en.wikipedia.org/wiki/Memoization). The canonical way to do that in C# is *not* with `Lazy` (because you'd need one Lazy instance for each possible parameter value), but rather with a dictionary. Here is an example: https://stackoverflow.com/q/20544641/87698 – Heinzi Jun 09 '22 at 19:57
  • Hey Bart dont forget to upvote and select a best answer – Nigel Jun 22 '22 at 20:19

1 Answers1

1

There are multiple problems here:

  • f1(x) returns int
    but the constructor for Lazy<int> requires a Func<int>.
  • x => new Lazy<int>(...); is of type Func<int,Lazy<int>> but your function returns Lazy<int>.

I'm not sure what your goal is but if you just wanted your code to compile you could do this:

 public static Lazy<int> memo2(Func<int, int> f1, int x) => new Lazy<int>(() => f1(x));
Nigel
  • 2,961
  • 1
  • 14
  • 32
  • Or maybe it was intended to be `Func> memo2(Func f1) => x => new Lazy(() => f1(x));` ? – Wyck Jun 09 '22 at 19:50
  • @Wyck Yea it's impossible to tell what the actual intent was from the question – Nigel Jun 09 '22 at 19:51
  • Because we are all in the dark here as to the OP's intent, it is better to comment rather than answer, until we get ,(hopefully) some clarity. – Jonathan Willcock Jun 09 '22 at 19:55
  • 1
    @JonathanWillcock I think my answer explains the compiler errors that OP is clearly having difficulty with – Nigel Jun 09 '22 at 19:58