language-ext Task of Either with multiple from clauses - language-ext

I am learning FP with language-ext and I ran into a problem that I have not been able to overcome. I simplified my code down to this example:
using System;
using System.Threading.Tasks;
using LanguageExt;
using static LanguageExt.Prelude;
using Xunit;
namespace Temp {
public class SelectManyError {
[Fact]
public async Task Do() {
var six = await from a in Task.FromResult(Right<Exception, int>(1))
from b in Task.FromResult(Right<Exception, int>(2))
from c in Task.FromResult(Right<Exception, int>(3))
select a + b + c;
}
}
}
I am getting this error:
Multiple implementations of the query pattern were found for source type Task<Either<Exception, int>>. Ambiguous call to 'SelectMany'.
I understand what the compiler thinks the issue is from reading this webpage. But, I am clearly missing or not understanding something important because I cannot figure out how this error is caused by this scenario OR what to do about it. This will work just fine if it is only 2 from clauses, which confuses me even more.
Is this the wrong approach to this type of problem? Is there another way I am unaware of?

Lang-ext author here. We've been discussing the issue on the lang-ext github repo.
These are my comments:
It's tough. They're not really false positives to be honest, because Either<L, R> supports the + operator, and so the SelectMany that belongs to Task<R> will produce a valid result just like the SelectMany that works with Task<Either<L, R>>.
Basically the a, b, and c values could legitimately be int or Either<Exception, int> depending on which SelectMany implementation the compiler chooses.
The whole expression is valid for all SelectMany extensions, which is obviously why we have that ambiguity.
It's a shame that changing var three = ... to Either<Exception, int> three = ... doesn't change the inference system. Because that's the key difference between the two possible expressions that the compiler is confused by.
One thing you might want to do instead of using Task<Option<A>> is use OptionAsync<A> and instead of Task<Either<L, R>> use EitherAsync<L, R>. They're essentially exactly the same types, except it's got all the binding semantics wrapped up nicely so you'll never have this issue again.
I am going through the process of creating an *Async variant for all the monadic types in lang-ext. For convenience, potential performance benefits, and to allow the equivalent of 3 nested levels of monads: M<A<B<C>>> for example a Seq<OptionAsync<A>> is the same as Seq<Task<Option<A>>>.
Anyway, back to your example above, you could instead do:
public async Task<int> Method()
{
var six = from a in Right<Exception, int>(1).ToAsync()
from b in Right<Exception, int>(2).ToAsync()
from c in Right<Exception, int>(3).ToAsync()
select a + b + c;
return await six.IfLeft(0);
}
Or if you want to construct from a Task<int>:
public async Task<int> Method()
{
var six = from a in RightAsync<Exception, int>(Task.FromResult(1))
from b in RightAsync<Exception, int>(Task.FromResult(2))
from c in RightAsync<Exception, int>(Task.FromResult(3))
select a + b + c;
return await six.IfLeft(0);
}
Or, you could stay inside the monad and return that:
public EitherAsync<Exception, int> Method() =>
from a in RightAsync<Exception, int>(Task.FromResult(1))
from b in RightAsync<Exception, int>(Task.FromResult(2))
from c in RightAsync<Exception, int>(Task.FromResult(3))
select a + b + c;

The compiler is having a hard time understanding what the type of a is supposed to be (either int or Either<Exception, int>) since it is unused on the second from line.
Here is a awfully ugly workaround for this specific case. However, for any type, I think the hack can be adapted to work for that type.
using System;
using System.Threading.Tasks;
using LanguageExt;
using Xunit;
using static LanguageExt.Prelude;
public class Namespace
{
[Fact]
public async Task Method()
{
var six = await from a in Right<Exception, int>(1).AsTask()
from b in Right<Exception, int>(a - a + 2).AsTask()
from c in Right<Exception, int>(3).AsTask()
select a + b + c;
}
}

Another way to work around this is by using how the compiler searches for matching extension methods.
From the C# spec
The search [..] proceeds as follows:
Starting with the closest enclosing namespace declaration, continuing with each enclosing namespace declaration, and ending with the containing compilation unit, successive attempts are made to find a candidate set of extension methods:
If the given namespace or compilation unit directly contains non-generic type declarations Cᵢ with eligible extension methods Mₑ, then the set of those extension methods is the candidate set.
If namespaces imported by using namespace directives in the given namespace or compilation unit directly contain non-generic type declarations Cᵢ with eligible extension methods Mₑ, then the set of those extension methods is the candidate set.
So .. if you add your own version of the extension methods needed for the LINQ query syntax to work (Select and SelectMany) within your application, at the same or a higher level in the namespace hierarchy as the calling code, these will be used and the two ambiguous versions in the LanguageExt namespace will never be considered.
Your extensions can just delegate to the generated source code in LanguageExt.Transformers.
Here I'm using Task<Validation< rather than Task<Either<; just check the source-code for the extensions class name of the particular combination of stacked monads you are using:
using System;
using System.Threading.Tasks;
using LanguageExt;
namespace YourApplication;
public static class BindDisambiguationExtensions
{
public static Task<Validation<FAIL, B>> Select<FAIL, A, B>(
this Task<Validation<FAIL, A>> ma,
Func<A, B> f) =>
ValidationT_AsyncSync_Extensions.Select(ma, f);
public static Task<Validation<FAIL, C>> SelectMany<FAIL, A, B, C>(
this Task<Validation<FAIL, A>> ma,
Func<A, Task<Validation<FAIL, B>>> bind,
Func<A, B, C> project) =>
ValidationT_AsyncSync_Extensions.SelectMany(ma, bind, project);
}

Related

Get declarations from an external source in Xtext

I have the following grammar:
Model: declarations += Declaration* statements += Statement*;
Declaration: 'Declare' name=ID;
Statement: 'Execute' what=[Declaration];
With that I can write simple scripts like:
Declare step_forward
Declare turn_right
Declare turn_left
Execute step_forward
Execute turn_left
Execute step_forward
Now I want that the java program provides all declarations, so that the script only contains the Execute statements. I read about IGlobalScopeProvider which seems to be the right tool for the job, but I have no idea how to add my data to it, and how to make Xtext use it.
So, how can I provide declarations from external to my grammar?
Update
My goal was somewhat unclear, so I try to make it more concrete. I want to keep the declarations as simple java objects, for instance:
List<Move> declarations = Arrays.asList(
new Move("step_forward"),
new Move("turn_right"),
new Move("turn_left"));
and the script should be:
Execute step_forward
Execute turn_left
Execute step_forward
I'm not really sure what you are asking for. After thinking about it, I cand derive th following possible questions:
1.) You want to split your script into two files. File a will only contain your declarations and File b then will only contain Statements. But any 'what' attribute will hold a reference to the declarations of File a.
This works out of the box with your grammar.
2.) You have any Java source code which provides a class which defines, for example a 'Declare Interface', and you want the 'what' attribute to reference to this interface or to classes which implement this interface.
Updated answer You should use Xbase within your language. There you can define that your 'what' attribute references to any Java type using the Xtypes rule 'JvmTypeReference'. The modifications you have to within your grammar are not that difficult, I think it could look this:
// Grammar now inherits from the Xbase grammar
// instead of the common terminals grammar
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.xbase.Xbase
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
Model:
declarator=Declarator?
statements+=Statement*;
Declarator:
'Declare' name=ID;
Statement:
'Execute' what=JvmTypeReference;
The, you can refer to any Java type (Java API, any linked API, user-defined types) by adressing them with their qualified name. It would look like this:
Referring to JVM types look like this in an Xtext language. (Screenshot)
You can also validate whether the referenced JVM type is valid, e.g. implements a desired interface which I would define with one single, optional declarator in the model.
Referenced JVM type is checked whether it is a valid type. (Screenshot)
With Xbase it is very easy to infer a Java interface for this model element. Use the generated stub '...mydsl.MyDslJvmModelInferrer':
class MyDslJvmModelInferrer extends AbstractModelInferrer {
#Inject extension JvmTypesBuilder
#Inject extension TypeReferences
def dispatch void infer(Model element, IJvmDeclaredTypeAcceptor acceptor, boolean isPreIndexingPhase) {
acceptor.accept(
element.declaration.toInterface('declarator.' + element.declaration.name) [
members += it.toMethod("execute", TypesFactory.eINSTANCE.createJvmVoid.createTypeRef)[]
])
}
}
It derives a single interface, named individually with only one method 'execute()'.
Then, implement static checks like this, you should use the generated stub '...mydsl.validation.MyDslValidator' In my example it is very quick and dirty, but you should get the idea of it:
class MyDslValidator extends AbstractMyDslValidator {
#Check
def checkReferredType(Statement s) {
val declarator = (s.eContainer as Model).declaration.name
for (st : (s.what.type as JvmDeclaredType).superTypes) {
if (st.qualifiedName.equals('declarator.' + declarator)) {
return
}
}
(s.what.simpleName + " doesn't implement the declarator interface " + declarator).
warning(MyDslPackage.eINSTANCE.statement_What)
}
}
(I used the preferred Xtend programming language to implement the static checking!) The static check determines if the given JvmTypeReference (which is a Java class from your project) implements the declared interface. Otherwise it will introduce a warning to your dsl document.
Hopefully this will answer your question.
Next update: Your idea will not work that well! You could simply write a template with Xtend for that without using Xbase, but I cannot imagine how to use it in a good way. The problem is, I assume, you don't to generate the hole class 'Move' and the hole execution process. I have played around a little bit trying to generate usable code and seems to be hacky! Neverthess, here is my solution:
Xtext generated the stub '...mydsl.generator.MyDslGenerator' for you with the method 'void doGenerate'. You have to fill this method. My idea is the following: First, you generate an abstract and generic Executor class with two generic parameters T and U. My executor class then has an abstract method 'executeMoves()' with the return value T. If this should be void use the non-primitive 'Void' class. It holds your List, but of the generic type u which is defined as a subclass of a Move class.
The Move class will be generated, too, but only with a field to store the String. It then has to be derived. My 'MyDslGenerator' looks like that:
class MyDslGenerator implements IGenerator {
static var cnt = 0
override void doGenerate(Resource resource, IFileSystemAccess fsa) {
cnt = 0
resource.allContents.filter(typeof(Model)).forEach [ m |
fsa.generateFile('mydsl/execution/Move.java', generateMove)
fsa.generateFile('mydsl/execution/Executor' + cnt++ + '.java', m.generateExecutor)
]
}
def generateMove() '''
package mydsl.execution;
public class Move {
protected String s;
public Move(String s) {
this.s = s;
}
}
'''
def generateExecutor(Model m) '''
package mydsl.execution;
import java.util.List;
import java.util.Arrays;
/**
* The class Executor is abstract because the execution has to implemented somewhere else.
* The class Executor is generic because one does not know if the execution has a return
* value. If it has no return value, use the not primitive type 'Void':
* public class MyExecutor extends Executor_i<Void> {...}
*/
public abstract class Executor«cnt - 1»<T, U extends Move> {
#SuppressWarnings("unchecked")
private List<U> declarations = Arrays.<U>asList(
«FOR Statement s : m.statements»
(U) new Move("«s.what.name»")«IF !m.statements.get(m.statements.size - 1).equals(s)»,«ENDIF»
«ENDFOR»
);
/**
* This method return list of moves.
*/
public List<U> getMoves() {
return declarations;
}
/**
* The executor class has to be extended and the extending class has to implement this
* method.
*/
public abstract T executeMoves();
}'''
}

Why Dart does not allow mixin inheritance?

Dart does not support true mixin composition like Scala does.
library some_lib;
// mixin A
abstract class A {
String get a => 'A';
}
// mixin B
abstract class B extends Object with A {
String get b => a + 'B';
}
Client usage
import 'some_lib.dart';
// client usage
class Client extends Object with B {
String get c => b + 'C';
}
void main(){
print(new Client().c); // should print ABC
}
Dart analyzer complains saying "The class 'B' cannot be used as a mixin because it extends a class other than Object"
I know you would reply that the following works fine:
class C extends Object with A, B {
String get c => a + b;
}
But I'm designing a library that will export some mixins that share some common functionality (provided by a base mixin), witch is relevant to their behavior, but irrelevant to my library clients.
I would even want to make this base mixin private if possible.
Any thoughts on that?
The specs for this are still evolving. I think they intend to implement full mixin based inheritance in the future releases.
That is what I gleaned from Gilad Bracha's (the brains behind the dart specs) talk here (fast forwarded to the appropriate section): http://youtu.be/yXY5bGlhxlw?t=18m42s

It is planned in Dart language adding functionality to declaring closures (without using typedef) as typed functions?

Closures in Dart language used very often because they very powerful.
I want ask question about closures usability.
Assume this source code:
class SomeWork<T> {
Function _test;
SomeWork(bool test(T a, T b)) {
_test = test;
}
}
If I rewrote this code as this code fragment then the function (as an argument) will be untyped (or rather will have a different type).
class SomeWork<T> {
final Function test;
SomeWork(this.test) {
}
}
Question:
It is planned in Dart language adding functionality to declaring closures (without using typedef, "on the fly") as typed functions?
Like this example of code:
class SomeWork<T> {
final Function<bool, T, T> test;
SomeWork(this.test) {
}
}
P.S.
For clarification I want add (after a while) this example in C# language because as I understand given example in the Dart language perceived not entirely correct.
class SomeWork<T> {
sealed Func<T, T, bool> m_test;
SomeWork(Func<T, T, bool> test)
{
m_test = test;
}
}
I.e. I asked about about possibility using types similar to C# Func<> and Action<>.
No, there are no plans here that I know of. Early in Dart's development, there were a number of discussions about this unfortunate corner of the type annotation syntax, but the language designers feel it's a worthwhile trade-off in order to have type annotations that look familiar to programmers coming from C, C++, Java, and C#.

setting breakpoint in WINDBG SOS with generically typed classes

Asking for help for the SOS extension command !BPMD in Windbg (i.e. typing !help BPMD) results in a text which contains, among other things, a description on how to break into generecally typed methods. This reads as follows:
!BPMD works equally well with generic types. Adding a breakpoint on a generic
type sets breakpoints on all already JIT-ted generic methods and sets a pending
breakpoint for any instantiation that will be JIT-ted in the future.
Example for generics:
Given the following two classes:
class G3<T1, T2, T3>
{
...
public void F(T1 p1, T2 p2, T3 p3)
{ ... }
}
public class G1<T> {
// static method
static public void G<W>(W w)
{ ... }
}
One would issue the following commands to set breapoints on G3.F() and
G1.G():
!bpmd myapp.exe G3`3.F
!bpmd myapp.exe G1`1.G
What I fail to understand here is the syntax used in the last two lines. What does the apostrophe (`) mean, and what is the meaning of the tho integers involved (the ones to the right of the apostrophe)? Are these codes related to the type (public void and static public void) of the methods, or do they refer to the number of template arguments? In case the first guess is true, where would I find a list of possible types?
The backtick symbol is the syntax for specifying a generic type in IL. The number after the backtick is the number of generic parameters.

MbUnit's row attribute in NUnit?

While reading an Asp.Net MVC code sample that used MbUnit as it's testing framework, I saw that it was possible to run a single test against multiple input possibilities by using a Row attribute, like so:
[Test]
[Row("test#test_test.com")]
[Row("sdfdf dsfsdf")]
[Row("sdfdf#.com")]
public void Invalid_Emails_Should_Return_False(string invalidEmail)
{
...
}
Please I'd like to know if there is an NUnit equivalent of MbUnit's Row attribute , or otherwise an elegant way to achieve this in NUnit. Thanks.
I think you're after the TestCase attribute
[TestCase(12,3,4)]
[TestCase(12,2,6)]
[TestCase(12,4,3)]
public void DivideTest(int n, int d, int q)
{
Assert.AreEqual( q, n / d );
}
http://www.nunit.com/index.php?p=testCase&r=2.5.7
NUnits Sequential attribute does exactly that.
The SequentialAttribute is used on a
test to specify that NUnit should
generate test cases by selecting
individual data items provided for the
parameters of the test, without
generating additional combinations.
Note: If parameter data is provided by
multiple attributes, the order in
which NUnit uses the data items is not
guaranteed. However, it can be
expected to remain constant for a
given runtime and operating system.
Example The following test will be
executed three times, as follows:
MyTest(1, "A")
MyTest(2, "B")
MyTest(3, null)
[Test, Sequential]
public void MyTest(
[Values(1,2,3)] int x,
[Values("A","B")] string s)
{
...
}
Given your example, this would become
[Test, Sequential]
public void IsValidEmail_Invalid_Emails_Should_Return_False(
[Values("test#test_test.com"
, "sdfdf dsfsdf"
, "sdfdf#.com")] string invalidEmail)
{
...
}

Resources