Bri*_*don 26 c# functional-programming
我正在使用C#中的一些功能性东西,并继续陷入List.Add不返回更新列表的事实.
一般来说,我想在一个对象上调用一个函数然后返回更新的对象.
例如,如果C#有一个逗号运算符会很棒:
((accum, data) => accum.Add(data), accum)
Run Code Online (Sandbox Code Playgroud)
我可以像这样编写自己的"逗号运算符":
static T comma(Action a, Func<T> result) {
a();
return result();
}
Run Code Online (Sandbox Code Playgroud)
它看起来会起作用但呼叫网站会很难看.我的第一个例子是:
((accum, data) => comma(accum.Add(data), ()=>accum))
Run Code Online (Sandbox Code Playgroud)
足够的例子!如果没有其他开发人员出现并且在代码味道上皱起鼻子,最干净的方法是什么?
dev*_*vio 17
我知道这是流利的.
使用扩展方法的List.Add的流畅示例
static List<T> MyAdd<T>(this List<T> list, T element)
{
list.Add(element);
return list;
}
Run Code Online (Sandbox Code Playgroud)
我知道这个帖子很老了,但我想为将来的用户添加以下信息:
目前没有这样的运营商.在C#6开发周期semicolon operator中添加了a ,如下:
int square = (int x = int.Parse(Console.ReadLine()); Console.WriteLine(x - 2); x * x);
Run Code Online (Sandbox Code Playgroud)
可以翻译如下:
int square = compiler_generated_Function();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int compiler_generated_Function()
{
int x = int.Parse(Console.ReadLine());
Console.WriteLine(x - 2);
return x * x;
}
Run Code Online (Sandbox Code Playgroud)
但是,在最终的C#版本发布之前,此功能已被删除.
这就是Concat http://msdn.microsoft.com/zh-cn/library/vstudio/bb302894%28v=vs.100%29.aspx的用途。只需将单个项目包装在数组中即可。功能代码不应更改原始数据。如果性能是一个问题,而这还不够好,那么您将不再使用功能范式。
((accum, data) => accum.Concat(new[]{data}))
Run Code Online (Sandbox Code Playgroud)
您自然可以在C#3.0中使用代码块来完成几乎第一个示例。
((accum, data) => { accum.Add(data); return accum; })
Run Code Online (Sandbox Code Playgroud)
另一种直接来自函数式编程的技术如下。像这样定义一个 IO 结构:
/// <summary>TODO</summary>
public struct IO<TSource> : IEquatable<IO<TSource>> {
/// <summary>Create a new instance of the class.</summary>
public IO(Func<TSource> functor) : this() { _functor = functor; }
/// <summary>Invokes the internal functor, returning the result.</summary>
public TSource Invoke() => (_functor | Default)();
/// <summary>Returns true exactly when the contained functor is not null.</summary>
public bool HasValue => _functor != null;
X<Func<TSource>> _functor { get; }
static Func<TSource> Default => null;
}
Run Code Online (Sandbox Code Playgroud)
并使用以下扩展方法使其成为支持 LINQ 的 monad:
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class IO {
public static IO<TSource> ToIO<TSource>( this Func<TSource> source) {
source.ContractedNotNull(nameof(source));
return new IO<TSource>(source);
}
public static IO<TResult> Select<TSource,TResult>(this IO<TSource> @this,
Func<TSource,TResult> projector
) =>
@this.HasValue && projector!=null
? New(() => projector(@this.Invoke()))
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,TResult>(this IO<TSource> @this,
Func<TSource,IO<TResult>> selector
) =>
@this.HasValue && selector!=null
? New(() => selector(@this.Invoke()).Invoke())
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,T,TResult>(this IO<TSource> @this,
Func<TSource, IO<T>> selector,
Func<TSource,T,TResult> projector
) =>
@this.HasValue && selector!=null && projector!=null
? New(() => { var s = @this.Invoke(); return projector(s, selector(s).Invoke()); } )
: Null<TResult>();
public static IO<TResult> New<TResult> (Func<TResult> functor) => new IO<TResult>(functor);
private static IO<TResult> Null<TResult>() => new IO<TResult>(null);
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用 LINQ综合语法,因此:
using Xunit;
[Fact]
public static void IOTest() {
bool isExecuted1 = false;
bool isExecuted2 = false;
bool isExecuted3 = false;
bool isExecuted4 = false;
IO<int> one = new IO<int>( () => { isExecuted1 = true; return 1; });
IO<int> two = new IO<int>( () => { isExecuted2 = true; return 2; });
Func<int, IO<int>> addOne = x => { isExecuted3 = true; return (x + 1).ToIO(); };
Func<int, Func<int, IO<int>>> add = x => y => { isExecuted4 = true; return (x + y).ToIO(); };
var query1 = ( from x in one
from y in two
from z in addOne(y)
from _ in "abc".ToIO()
let addOne2 = add(x)
select addOne2(z)
);
Assert.False(isExecuted1); // Laziness.
Assert.False(isExecuted2); // Laziness.
Assert.False(isExecuted3); // Laziness.
Assert.False(isExecuted4); // Laziness.
int lhs = 1 + 2 + 1;
int rhs = query1.Invoke().Invoke();
Assert.Equal(lhs, rhs); // Execution.
Assert.True(isExecuted1);
Assert.True(isExecuted2);
Assert.True(isExecuted3);
Assert.True(isExecuted4);
}
Run Code Online (Sandbox Code Playgroud)
当需要一个 IO monad 组合但只返回void 时,定义这个结构体和依赖方法:
public struct Unit : IEquatable<Unit>, IComparable<Unit> {
[CLSCompliant(false)]
public static Unit _ { get { return _this; } } static Unit _this = new Unit();
}
public static IO<Unit> ConsoleWrite(object arg) =>
ReturnIOUnit(() => Write(arg));
public static IO<Unit> ConsoleWriteLine(string value) =>
ReturnIOUnit(() => WriteLine(value));
public static IO<ConsoleKeyInfo> ConsoleReadKey() => new IO<ConsoleKeyInfo>(() => ReadKey());
Run Code Online (Sandbox Code Playgroud)
这很容易允许编写这样的代码片段:
from pass in Enumerable.Range(0, int.MaxValue)
let counter = Readers.Counter(0)
select ( from state in gcdStartStates
where _predicate(pass, counter())
select state )
into enumerable
where ( from _ in Gcd.Run(enumerable.ToList()).ToIO()
from __ in ConsoleWrite(Prompt(mode))
from c in ConsoleReadKey()
from ___ in ConsoleWriteLine()
select c.KeyChar.ToUpper() == 'Q'
).Invoke()
select 0;
Run Code Online (Sandbox Code Playgroud)
旧的C逗号运算符很容易识别它是什么:一元组合操作。
当人们尝试以流畅的风格编写该片段时,理解语法的真正优点是显而易见的:
( Enumerable.Range(0,int.MaxValue)
.Select(pass => new {pass, counter = Readers.Counter(0)})
.Select(_ => gcdStartStates.Where(state => _predicate(_.pass,_.counter()))
.Select(state => state)
)
).Where(enumerable =>
( (Gcd.Run(enumerable.ToList()) ).ToIO()
.SelectMany(_ => ConsoleWrite(Prompt(mode)),(_,__) => new {})
.SelectMany(_ => ConsoleReadKey(), (_, c) => new {c})
.SelectMany(_ => ConsoleWriteLine(), (_,__) => _.c.KeyChar.ToUpper() == 'Q')
).Invoke()
).Select(list => 0);
Run Code Online (Sandbox Code Playgroud)