I\'m trying to figure out how to write recursive functions (e.g. factorial, although my functions are much more complicated) in one line. To do this, I thought of using the
Here's the implementation of the Y-combinator that I use in c#:
public delegate T S(S s);
public static T U(S s)
{
return s(s);
}
public static Func Y(Func, Func> f)
{
return U>(r => a => f(U(r))(a));
}
I can use it like:
var fact = Y(_ => x => x == 0 ? 1 : x * _(x - 1));
var fibo = Y(_ => x => x <= 1 ? 1 : _(x - 1) + _(x - 2));
It truly scares me, so I'll leave the next two parts of your question to you, given this as a starting point.
I've had a crack at the function.
Here it is:
var allsubstrings =
Y>
(_ => x => x.Length == 1
? new [] { x }
: Enumerable
.Range(0, x.Length)
.SelectMany(i =>
_(x.Remove(i, 1))
.SelectMany(z => new [] { x.Substring(i, 1) + z, z }))
.Distinct());
Of course, you run it like this:
allsubstrings("abcd");
From which I got this result:
abcd
bcd
acd
cd
abd
bd
ad
d
abdc
bdc
adc
dc
abc
bc
ac
c
acbd
cbd
acdb
cdb
adb
db
acb
cb
ab
b
adbc
dbc
adcb
dcb
bacd
bad
badc
bac
bcad
cad
bcda
cda
bda
da
bca
ca
ba
a
bdac
dac
bdca
dca
cabd
cadb
cab
cbad
cbda
cba
cdab
dab
cdba
dba
dabc
dacb
dbac
dbca
dcab
dcba
It seems that your non-Y-Combinator code in your question missed a bunch of permutations.