Un ancien Yet Another Language Geek blog post expliquant monades décrit l'ajout d'une méthode d'extension SelectMany à C# afin d'étendre la syntaxe linq à de nouveaux types. Je l'ai essayé en C# et cela fonctionne. J'ai fait une conversion directe à VB.net et ça ne marche pas. Est-ce que quelqu'un sait si VB.net supporte cette fonctionnalité ou comment l'utiliser?Ajout de C# SelectMany étend linq à un nouveau type monad, comment faire la même chose sur VB.net?
Voici le code C# qui fonctionne:
class Identity<T> {
public readonly T Value;
public Identity(T value) { this.Value = value; }
}
static class MonadExtension {
public static Identity<T> ToIdentity<T>(this T value) {
return new Identity<T>(value);
}
public static Identity<V> SelectMany<T, U, V>(this Identity<T> id, Func<T, Identity<U>> k, Func<T, U, V> s) {
return s(id.Value, k(id.Value).Value).ToIdentity();
}
}
class Program {
static void Main(string[] args) {
var r = from x in 5.ToIdentity()
from y in 6.ToIdentity()
select x + y;
}
}
Voici le code VB.net qui ne fonctionne pas (note: écrit en VS2010, donc peut manquer quelques continuités de ligne):
Imports System.Runtime.CompilerServices
Public Class Identity(Of T)
Public ReadOnly value As T
Public Sub New(ByVal value As T)
Me.value = value
End Sub
End Class
Module MonadExtensions
<Extension()> _
Public Function ToIdentity(Of T)(ByVal value As T) As Identity(Of T)
Return New Identity(Of T)(value)
End Function
<Extension()> _
Public Function SelectMany(Of T, U, V)(ByVal id As Identity(Of T), ByVal k As Func(Of T, Identity(Of U)), ByVal s As Func(Of T, U, V)) As Identity(Of V)
Return s(id.value, k(id.value).value).ToIdentity()
End Function
End Module
Public Module MonadTest
Public Sub Main()
''Error: Expression of type 'Identity(Of Integer)' is not queryable.
Dim r = From x In 5.ToIdentity() _
From y In 6.ToIdentity() _
Select x + y
End Sub
End Module
J'ai inclus un exemple de code dans la question maintenant, ainsi vous pouvez vérifier si j'ai traduit correctement. –