Nullable可以用作C#中的函子吗? [英] Can Nullable be used as a functor in C#?
问题描述
在C#中考虑以下代码.
Consider the following code in C#.
public int Foo(int a)
{
// ...
}
// in some other method
int? x = 0;
x = Foo(x);
最后一行将返回编译错误cannot convert from 'int?' to 'int'
,这很合理.但是,例如在Haskell中有Maybe
,它与C#中的Nullable
对应.由于Maybe
是Functor
,因此我可以使用fmap
将Foo
应用于x
. C#是否具有类似的机制?
The last line will return a compilation error cannot convert from 'int?' to 'int'
which is fair enough. However, for example in Haskell there is Maybe
which is a counterpart to Nullable
in C#. Since Maybe
is a Functor
I would be able to apply Foo
to x
using fmap
. Does C# have a similar mechanism?
推荐答案
我们可以自己实现此类功能:
We can implement such functionality ourselves:
public static class FuncUtils {
public static Nullable<R> Fmap<T, R>(this Nullable<T> x, Func<T, R> f)
where T : struct
where R : struct {
if(x != null) {
return f(x.Value);
} else {
return null;
}
}
}
然后我们可以将其用于:
Then we can use it with:
int? x = 0;
x = x.Fmap(Foo);
如果x
不是null
,它将因此调用函数Foo
.它将结果包装回Nullable<R>
中.如果x
是null
,它将返回带有null
的Nullable<R>
.
It will thus call the function Foo
if x
is not null
. It will wrap the result back in a Nullable<R>
. In case x
is null
, it will return a Nullable<R>
with null
.
或者我们可以编写一个更等效的函数(例如Haskell中的fmap
),其中我们有一个函数Fmap
,该函数将Func<T, R>
作为输入并返回Func<Nullable<T>, Nullable<R>>
,这样我们就可以将其用于某些x
:
Or we can write a more equivalent function (like fmap
in Haskell) where we have a function Fmap
that takes as input a Func<T, R>
and returns a Func<Nullable<T>, Nullable<R>>
so that we can then use it for a certain x
:
public static class FuncUtils {
public static Func<Nullable<T>, Nullable<R>> Fmap<T, R>(Func<T, R> f)
where T : struct
where R : struct {
return delegate (Nullable<T> x) {
if(x != null) {
return f(x.Value);
} else {
return null;
}
};
}
}
然后我们可以像这样使用它:
We can then use it like:
var fmapf = FuncUtils.Fmap<int, int>(Foo);
fmapf(null); // -> null
fmapf(12); // -> Foo(12) as int?
这篇关于Nullable可以用作C#中的函子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!