我在 C# 中编写了一个有点惰性的 IO 类型的 monad,并尝试使用 linq 语法使代码更具可读性。
有没有一种方法可以在没有变量分配的情况下对那些因副作用而被调用的操作进行绑定?
在Print(...)
这个例子中总是返回Void.Void
:
static IO<Void> Foo()
{
var foo = from i in Return(2)
from _1 in Print("Enter a number")
from input in ReadInt()
from _2 in Print("You entered: " + input)
from j in Increment(input).Bind(Square)
from sum in Add(j, input)
from _3 in Print("i = " + i)
from _4 in Print("j = " + j)
from condition in GreaterThan(j, 10)
from _5 in If(condition,
Print("j is greater than 10"),
Print("j is not greater than 10"))
from _6 in Print("sum = " + sum)
select Void.Void;
return foo;
}