【问题标题】:Railway Oriented programming in C# - How do I write the switch function?C# 中面向铁路的编程 - 如何编写 switch 函数?
【发布时间】:2016-06-26 01:34:59
【问题描述】:

我一直在关注this F# ROP article,并决定尝试用 C# 重现它,主要是看看我是否可以。抱歉这个问题太长了,但如果你熟悉 ROP,它会很容易理解。

他从一个 F# 有区别的联合开始......

type Result<'TSuccess, 'TFailure> =
  | Success of 'TSuccess
  | Failure of 'TFailure

...我将其翻译成一个抽象的 RopValue 类,以及两个具体的实现(请注意,我已将类名更改为我更好理解的类名)...

public abstract class RopValue<TSuccess, TFailure> {
  public static RopValue<TSuccess, TFailure> Create<TSuccess, TFailure>(TSuccess input) {
    return new Success<TSuccess, TFailure>(input);
  }
}

public class Success<TSuccess, TFailure> : RopValue<TSuccess, TFailure> {
  public Success(TSuccess value) {
    Value = value;
  }
  public TSuccess Value { get; set; }
}

public class Failure<TSuccess, TFailure> : RopValue<TSuccess, TFailure> {
  public Failure(TFailure value) {
    Value = value;
  }
  public TFailure Value { get; set; }
}

我添加了一个静态 Create 方法,允许您从 TSuccess 对象创建一个 RopValue,该对象将被输入到第一个验证函数中。

然后我开始编写一个绑定函数。 F#版本如下...

let bind switchFunction twoTrackInput =
  match twoTrackInput with
  | Success s -> switchFunction s
  | Failure f -> Failure f

...与 C# 等价物相比,这简直是轻而易举!我不知道是否有更简单的方法来写这个,但这是我想出的......

public static RopValue<TSuccess, TFailure> Bind<TSuccess, TFailure>(this RopValue<TSuccess, TFailure> input, Func<RopValue<TSuccess, TFailure>, RopValue<TSuccess, TFailure>> switchFunction) {
  if (input is Success<TSuccess, TFailure>) {
    return switchFunction(input);
  }
  return input;
}

请注意,我将其编写为扩展函数,因为它允许我以更实用的方式使用它。

以他验证一个人的用例,然后我写了一个 Person 类...

public class Person {
  public string Name { get; set; }
  public string Email { get; set; }
  public int Age { get; set; }
}

...并编写了我的第一个验证函数...

public static RopValue<Person, string> CheckName(RopValue<Person, string> res) {
  if (res.IsSuccess()) {
    Person person = ((Success<Person, string>)res).Value;
    if (string.IsNullOrWhiteSpace(person.Name)) {
      return new Failure<Person, string>("No name");
    }
    return res;
  }
  return res;
}

通过几个类似的电子邮件和年龄验证,我可以编写如下的整体验证函数...

private static RopValue<Person, string> Validate(Person person) {
  return RopValue<Person, string>
    .Create<Person, string>(person)
    .Bind(CheckName)
    .Bind(CheckEmail)
    .Bind(CheckAge);
}

这很好用,让我可以做这样的事情......

Person jim = new Person {Name = "Jim", Email = "", Age = 16};
RopValue<Person, string> jimChk = Validate(jim);
Debug.WriteLine("Jim returned: " + (jimChk.IsSuccess() ? "Success" : "Failure"));

但是,我在执行此操作时遇到了一些问题。首先是验证函数要求你传入一个 RopValue,检查它是否成功或失败,如果成功,则取出 Person 然后验证它。如果失败,直接返回即可。

相比之下,他的验证函数接受(相当于)一个 Person,并返回(一个 Result,相当于)一个 RopValue...

let validateNameNotBlank person =
  if person.Name = "" then Failure "Name must not be blank"
  else Success person

这要简单得多,但我无法弄清楚如何在 C# 中执行此操作。

另一个问题是我们以 Success 开始验证链,因此第一个验证函数将始终从“if”块返回一些内容,如果验证失败则返回 Failure,如果验证失败则返回 Success我们通过了检查。如果一个函数返回 Failure,那么验证链中的下一个函数永远不会被调用,因此我们知道这些方法永远不能传递一个 Failure。因此,永远无法到达这些函数的最后一行(除了您手动创建一个 Failure 并在开始时将其传递的奇怪情况,但那将毫无意义)。

然后他创建了一个开关运算符 (>=>) 来连接验证函数。我试过这样做,但无法让它工作。为了链接对函数的连续调用,看起来我必须在 Func 上有一个扩展方法,我认为你不能这样做。我已经做到了……

public static RopValue<TSuccess, TFailure> Switch<TSuccess, TFailure>(this Func<TSuccess, RopValue<TSuccess, TFailure>> switch1, Func<TSuccess, RopValue<TSuccess, TFailure>> switch2, TSuccess input) {
  RopValue<TSuccess, TFailure> res1 = switch1(input);
  if (res1.IsSuccess()) {
    return switch2(((Success<TSuccess, TFailure>)res1).Value);
  }
  return new Failure<TSuccess, TFailure>(((Failure<TSuccess, TFailure>)res1).Value);
}

...但不知道如何使用它。

那么,谁能解释我将如何编写 Bind 函数,以便它可以接受一个 Person 并返回一个 RopValue(就像他的那样)?另外,如何编写一个允许我连接简单验证功能的开关功能?

欢迎使用我的代码中的任何其他 cmets。我不确定它是否尽可能简洁。

【问题讨论】:

  • 这一切都让我觉得类似于Error&lt;T&gt; monad。你觉得它是,但TFailure 类型实际上等同于Exception
  • @Enigmativity 引用马克吐温的话,“我很高兴能够快速回答,我说我不知道​​!” - 我是一名 C# 程序员,同时学习 F# 和函数式编程。我见过讨论单子,但还没有弄清楚它们是什么。
  • 你的 RopValue 类型是一个单子。基本上单子赋予普通类型超能力。
  • @AvrohomYisroel 您可以将 monad 视为函数式程序员使用的一种设计模式。您已经熟悉的一个简单示例是 List monad,它基本上是 LINQ 的一个实现。这里bind 函数称为SelectMany,如果您查看该函数的类型签名,您会发现它与我在答案中显示的形式相匹配。 Monad 还允许您做一些更有趣的事情,例如创建一个引用透明的跟踪状态的方式。
  • @Enigmativity "基本上单子赋予普通类型超能力" - 有点像编码世界的 X-Kryptonite 嗯?

标签: c# f# functional-programming


【解决方案1】:

您的Bind 函数类型错误,应该是:

public static RopValue<TOut, TFailure> Bind<TSuccess, TFailure, TOut>(this RopValue<TSuccess, TFailure> input, Func<TSuccess, RopValue<TOut, TFailure>> switchFunction) {
  if (input is Success<TSuccess, TFailure>) {
    return switchFunction(((Success<TSuccess, TFailure>)input).Value);
  }
  return new Failure<TOut, TFailure>(((Failure<TSuccess, TFailure>)input).Value);
}

传递给Bind 实现的Func 参数采用RopValue&lt;TSuccess, TFailure&gt; 参数,而不仅仅是TSuccess。这意味着该函数需要在输入上重复 Bind 方法应该为您执行的相同匹配。

由于类型参数的数量,这可能有点笨拙,因此您可以将其移至基类:

public abstract RopValue<TOut, TFailure> Bind<TOut>(Func<TSuccess, RopValue<TOut, TFailure> f);

public class Success<TSuccess, TFailure> : RopValue<TSuccess, TFailure> {
    public override RopValue<TOut, TFailure> Bind<TOut>(Func<TSuccess, RopValue<TOut, TFailure> f) {
        return f(this.Value);
    }
}

public class Failure<TSuccess, TFailure> : RopValue<TSuccess, TFailure> {
    public override RopValue<TOut, TFailure> Bind<TOut>(Func<TSuccess, RopValue<TOut, TFailure> f) {
        return new Failure<TOut, TFailure>(this.Value);
    }
}

然后您可以避免在链的开头创建一个虚拟值:

private static RopValue<Person, string> Validate(Person person) {
  return CheckName(person)
    .Bind(CheckEmail)
    .Bind(CheckAge);
}

【讨论】:

  • 现在有机会看看这个。当您说我的 Bind 函数的类型错误时,据我所知,唯一真正的区别是您纠正了我假设输入和输出类型相同的潜意识简化。不知道为什么这会改变你在我的情况下使用它的方式,因为我一直在使用 Person 类。你能再解释一下吗?
  • 另外,我尝试将 Bind 函数移动到基类,这对 Success 来说很好,因为我刚刚返回了 switchFunction(Value),但我无法弄清楚 Failure 类中的内容。我的想法是返回“this”(作为 Failure 对象本身,它当然也是一个 RopValue 对象),但这给出了一个编译器错误,它无法将 Failure 转换为 RopValue。铸造也没有帮助。我在这里错过了什么?再次感谢
【解决方案2】:

Lee 是正确的,您的绑定函数定义不正确。

Bind 应该始终有一个类似这样的类型签名:m&lt;'a&gt; -&gt; ('a -&gt; m&lt;'b&gt;) -&gt; m&lt;'b&gt;

我是这样定义的,但 Lee 的功能是相同的:

public static RopValue<TSuccess2, TFailure> Bind<TSuccess, TSuccess2, TFailure>(this RopValue<TSuccess, TFailure> input, Func<TSuccess, RopValue<TSuccess2, TFailure>> switchFunction)
{
    if (input.IsSuccess)
    {
        return switchFunction(((Success<TSuccess,TFailure>)input).Value);
    }
    return new Failure<TSuccess2, TFailure>(((Failure<TSuccess, TFailure>)input).Value);
}

Kleisli Composition (&gt;=&gt;) 的类型签名类似于:('a -&gt; m&lt;'b&gt;) -&gt; ('b -&gt; m&lt;'c&gt;) -&gt; 'a -&gt; m&lt;'c&gt;

您可以使用绑定来定义:

public static Func<TSuccess, RopValue<TSuccess2, TFailure>> Kleisli<TSuccess, TSuccess2, TFailure>(this Func<TSuccess, RopValue<TSuccess, TFailure>> switch1, Func<TSuccess, RopValue<TSuccess2, TFailure>> switch2)
{
    return (inp => switch1(inp).Bind(switch2));
}

您可以在 Func 上定义扩展方法,但诀窍是让编译器看到这些扩展方法可用,这样可以工作:

Func<Entry, RopValue<Request, string>> checkEmail = CheckEmail;
var combined = checkEmail.Kleisli(CheckAge);
RopValue<Request, string> result = combined(request);

request 是您要验证的数据。

请注意,通过创建Func 类型的变量,它允许我们使用扩展方法。

【讨论】:

  • 我的回答确实允许更改成功类型,这就是 TOut 参数的用途。
  • @Lee 你说得对,我很抱歉,我显然要疯了。
猜你喜欢
  • 2019-10-08
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
  • 2022-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多