Is there a use of a delegate type that returns a delegate of the same type as itself?

I worked in Visual Studio and I found that

delegate RecursiveDelegate RecursiveDelegate(); 

- A valid delegate definition.

I don't have much experience with functional programming, but I was wondering if this template is really useful in functional programming, or if it's just a curiosity of semantics. I want to ask this question in two ways:

  • In the context of side effects. I see that this is actually halfway a decent way to model iterative learning algorithms in a functional language, where the actual task of the algorithm is performed as a side effect, and the new version of the function is the return value. It's done?
  • In a context without side effects. I think this is basically useless, but I am very curious if I am wrong. Could this be useful if we assume that the implementation of RecursiveDelegate () has no side effects?
+4
source share
1 answer

I have an example of some similar code that is not an exact recursive delegate, but it is close. "Y-Combinator" is close - and to be honest, I have no idea how this works in practice, but it is used to define recursive functions.

Here is the funky code you need to define:

 public delegate T S<T>(S<T> s); public static T U<T>(S<T> s) { return s(s); } public static Func<A, Z> Y<A, Z>(Func<Func<A, Z>, Func<A, Z>> f) { return U<Func<A, Z>>(r => a => f(U(r))(a)); } 

Now you can define recursive functions in one line.

Factorial:

 var fact = Y<int, int>(_ => x => x == 0 ? 1 : x * _(x - 1)); var fact5 = fact(5); // == 120 var fact6 = fact(6); // == 720 var fact7 = fact(7); // == 5040 

Fibonacci:

 var fibo = Y<int, int>(_ => x => x <= 1 ? 1 : _(x - 1) + _(x - 2)); var fibo5 = fibo(5); // == 8 var fibo6 = fibo(6); // == 13 var fibo7 = fibo(7); // == 21 

My favorite line of code is calling s(s) . Seriously, if someone can straighten it out of their heads, they are a genius! Not to mention the whole U<Func<A, Z>>(r => a => f(U(r))(a)) .

+1
source

Source: https://habr.com/ru/post/1497536/


All Articles