【发布时间】:2018-09-26 20:00:03
【问题描述】:
我正在处理Functional Programming in C# by Enrico Buonanno
如何在 C# 中实现 Apply for the Either monad?我尝试了以下不类型检查:
using System;
using Xunit;
using LaYumba.Functional;
using static LaYumba.Functional.F;
namespace ch8
{
public class UnitTest1
{
[Fact]
public void Ex1()
{
Func<int, int, int> add = (x, y) => x + y;
var option = Some(add)
.Apply(3)
.Apply(2);
Assert.Equal(Some(5), option);
var either = Left(add)
.Apply(3) // does not type check
.Apply(2);
Assert.Equal(Left(5), either);
}
}
public static class Ext
{
public static Either<L, R> Apply<L, R>(
this Either<L, Func<R, R>> source, Either<L, R> target)
=> source.Match(
l => Left(l),
f => target.Match<Either<L, R>>(
l => Left(l),
r => Right(f(r))
));
}
}
我收到以下错误:
watch : Started
Build started, please wait...
UnitTest1.cs(22,16): error CS1061: 'Either.Left<Func<int, int, int>>' does not contain a definition for 'Apply' and no extension method 'Apply' accepting afirst argument of type 'Either.Left<Func<int, int, int>>' could be found (are you missing a using directive or an assembly reference?) [/ch8/ch8/ch8.csproj]
UnitTest1.cs(25,26): error CS1503: Argument 1: cannot convert from 'LaYumba.Functional.Either.Left<int>' to 'string' [/ch8/ch8/ch8.csproj]
UnitTest1.cs(25,35): error CS1503: Argument 2: cannot convert from 'LaYumba.Functional.Either<L, R>' to 'string' [/ch8/ch8/ch8.csproj]
watch : Exited with error code 1
watch : Waiting for a file to change before restarting dotnet...
我做错了什么?
【问题讨论】:
标签: c# functional-programming monads either