what is the difference between either and Option in dartz? - flutter

i am trying to understand dartz, but the documentation is not clear enough.
i need to get the difference between either and Option in dartz?
abstract class Option<A> implements TraversableMonadPlusOps<Option, A>
VS
abstract class Either<L, R> implements TraversableMonadOps<Either<L, dynamic>, R>

Well, an Option type normally is a type that holds either a typed value, or nothing.
For example if you want to get the first integer of a list of integers, that might be an Option<int> because it can be an int or nothing in case the list is empty. But it cannot be a string.
An Either type is just what the name says... either one or the other. And it can be two different types altogether. Either<int, string> would have either an int or a string. Never both. Never none. Either one or the other.
For example a functional ParseInt method might return a Either<int, string>, because it will return either a valid int, or an error message.

Related

What is the relationship of TypeMirrors and Elements in the lang model?

(While this question is tagged with annotation-processing I'm actually asking questions about the type model exposed by javax.lang.model whether or not annotation processing is involved.)
In javax.lang.model, there are two fundamental constructs: Elements and TypeMirrors.
Every Element is backed by a TypeMirror. However only certain TypeMirror subtypes, namely DeclaredType and TypeVariable, have Elements associated with them via DeclaredType#asElement() and TypeVariable#asElement() respectively.
(It follows that all Elements "have" TypeMirrors, but not all TypeMirrors "have" Elements.)
Speaking loosely and intuitively, this makes sense: you declare types by chanting certain Java spells: the spells themselves are the (declared) elements; the things they bring into being are the types that back them. I've programmed in Java for decades and have a good working familiarity with oddities like Foo implements Comparable<Foo>. I'm trying to get more rigorous here.
With all that in mind, and considering the following snippet, how are the javax.lang.model types and elements manifested?
// (Defined by the JDK itself of course.)
public interface Comparable<T> ...
// (My class.)
public class Frob implements Comparable<Frob> ...
I see the following "things", working from "top" to "bottom" with less and less certainty as I go along:
a TypeParameterElement whose affiliated Name is equal to "T"
The return value of its asType() method will be a (definitionally nameless) TypeVariable whose asElement() method will return the TypeParameterElement currently being discussed.
The return value of its getGenericElement() method (and its getEnclosingElement() method) will be the Element we'll talk about next ("Comparable").
a TypeElement whose affiliated Name is equal to "Comparable"
The return value of its asType() method will be a (definitionally nameless) DeclaredType whose asElement() method will return the TypeElement currently being discussed
The DeclaredType so returned will have exactly one type argument which will be the (definitionally nameless) TypeVariable discussed above whose asElement() method will return the TypeParameterElement discussed above ("T")
The return value of its getTypeParameters() method will consist solely of the TypeParameterElement discussed earlier.
a TypeElement whose affiliated Name is equal to "Frob".
(This TypeElement is brought into being with the Java syntax public class Frob ....)
The return value of its asType() method will be a (definitionally nameless) DeclaredType whose asElement() method will return the TypeElement currently being discussed.
The return value of its getInterfaces() method will be discussed in a moment.
an Element of some variety loosely described by "Comparable<Frob>".
I say "of some variety" because as written it itself does not have, say, an explicit or implicit extends or implements clause, or other markers I would expect to see of, say, a TypeElement. Nevertheless I'm not sure that it could be any other kind of Element other than a TypeElement. Maybe it is a TypeElement equal to that denoted by "Comparable<T>", but with its various TypeMirror-returning or -referencing methods using the type denoted by Frob?
The return value of its asType() method will be a (definitionally nameless) TypeMirror of some variety (almost certainly a DeclaredType) whose asElement() method will return the Element currently being discussed (this corresponds somewhat to java.lang.reflect.ParameterizedType in the runtime/reflection model)
The TypeMirror so returned will have exactly one type argument which will be the (definitionally nameless) DeclaredType returned by the asType() method of the TypeElement whose Name is equal to "Frob" described above
The TypeMirror so returned will be the sole member of the return value of the getInterfaces() method when invoked on the TypeElement whose Name is equal to "Frob" described above
Do I have this right as far as it goes?
Your question seems well-reasoned, and I can't find anything specifically wrong with it to point out to you, but it is missing the one vital truth of where Elements and TypeMirrors differ.
Elements represent nodes in the Java type AST that reside "on disk" - the code at rest, either in .java or .class files. Any class/interface/enum/record/annotation that exists on disk in this form is in some way discoverable by this. To get a bit further, these cover the entire API of any of those types above - any members (fields/constructors/methods or nested types, then also the params of those methods/ctors) and packages too are described by elements. But the Element hierarchy only covers the types on disk - to use a concrete example from your question, Comparable<T> and its Comparable<T>.compareTo(T) member, and that method's parameter are covered in this way. And yes, lest I omit the type parameter, both the class and the method have a type param embedded in their respective element - as an element.
On the other hand, TypeMirrors represent those elements "in use" - you can't really reason about Comparable<T> in your code, but instead will either use it raw (please don't), or will parameterize it in some specific way (such as Comparable<Frob>, Comparable<?>, or possibly Comparable<T> where T is the type param of an enclosing element such as the current method or class). This means that T is not the same TypeElement as above - it isn't the value of the TypeElement that was on disk, but is something more specific.
You'll find TypeMirrors in Elements (for example "what is the return type of the method that appears in this class?"), and all Elements can be converted to some form of TypeMirror. On the other hand, not all TypeMirrors can be converted to some Element (such as a primitive), or if they can, that conversion may be "lossy" (for example converting a TypeMirror of List<String> to an Element would give you only List<T> itself).

Swift generics: How to represent 'no type'?

I am using Google's promises library, and I would like to create promise without any type (because I don't need any).
However, I am being forced to pick some type:
let promise = Promise<SomeType>.pending()
Is there a type I could pass in place of SomeType that would essentialy mean 'no type', when I need promises just for async flow and exception catching, but I don't want to return a specific value from a function?
For example, some type whose only valid value is nil?
I have encountered this problem in multiple places, the only workaround I found so far is to always provide a non-generic alternative, but it gets really tedious and leads to duplicate code.
Types are sets of values, like Int is the set of all integer numbers, String is the set of all sequences of characters and so on.
If you consider the number of items in the set, there are some special types with 0 items and 1 items exactly, and are useful in special cases like this.
Never is the type with no values in it. No instance of a Never type can be constructed because there are no values that it can be (just like an enum with no cases). That is useful to mark situations, code flow etc as 'can't happen', for example the compiler can know that a function that returns Never, can never return. Or that a function that takes Never can never be called. A function that returns Result<Int, Never> will never fail, but is in the world of functions returning Result types. But because never can't be constructed it isn't what you want here. It would mean a Promise that can't be fulfilled.
Void is the type with exactly 1 value. It's normally spelled () on the left and Void on the right, of a function definition. The value of a void is not interesting. It's useful to make a function that returns Void because those are like what other languages call subroutines or procedures. In this case it means a Promise that can be fulfilled but not with any value. It can only be useful for its side effects, therefore.
Is it a correct solution or a workaround if we create an empty class
class Default_Class : Codable {
}
and use this as Promise<Default_Class>.pending

Is int type in Dart a value type or reference type?

The int type in Dart has default value of null. null is an object of type Null class. (as per Dart documentation). Also, in Dart, int derives from class Object.
Hence,
int i = 10;
print(i.runtimeType is Object); // returns true
This makes me believe that int is not a value type like in other languages (such as C#) but a reference type.
If I am correct, then-
int i = 10;
means i is a reference variable holding the reference to an int object 10.
Is this correct? If not, I would appreciate if a link to the description in the documentation is shared.
Till now, I've been unable to find any proper explanation and hence have come to this conclusion myself.
Thanks.
Yes, Dart's int type is a "reference type".
Dart does not have value types at all, all values are instances of a class, including integers. (At least technically, function values makes their classes very hard to see.)
Integers are immutable and pretends to be canonicalized.
If a and b are int values and a == b, then identical(a, b) is guaranteed to be true, so a and b looks like they are the same object, but it's unspecified whether that's because they really are the same object, or because identical just cheats and does == for integers.
That means that you can largely treat int as a "value type". Whether it is copied on assignment or parameter passing, or you are passing a reference to the same object, is impossible to tell apart. The language ensures that, because it allows the implementations to do whatever is more efficient.
In practice, some integers are unboxed inside functions, some integers are stored as a value in the reference itself, and some are real objects.
(That's also one of the reasons you can't use an Expando with an int).
(In the current Dart language, all types annotations are nullable, meaning that you can assign null to int x;. With the upcoming Null Safety feature, that changes. Types will only be nullable if you write them as such, so int x = 1; would not accept a null value, but int? x; would. And null is an object too, the only instance of the class Null.)
int is a value type in the sense that if you pass int value into a function and change the value of a parameter inside function, it won't affect outer scope.
void add(int inner) {
inner += 1;
}
int outer = 0;
add(outer);
print(outer); // 0, unchanged
But int is still a class even though its name starts from lowercase letter. There was a huge discussion about its naming and lots of people consider it an inconsistency.
Yes int is a class (it even extends num) and therefor has common methods to use on. But one the other side it is different than "normal" classes since you don't have to use a constructor like
int i = int(3);
See int's class documenation https://api.dart.dev/stable/2.8.4/dart-core/int-class.html
Everything in Dart is an object, int, double or num may look like keywords but they are built-in abstract classes. Since they are abstract classes which means they can not be instantiated, they do not start with an uppercase letter.
try this line,
print('2 is instance of "int" class :\t${ 2 is int}');
this will result in true.
And regarding your concern about 'null' :
In Dart, like JavaScript and Python, everything that a variable can hold is an object including null. Every object including null is an instance of some class and all these classes inherit from Object class.
your can refer this link for more info.
Hope this helps.

How to specify a List<MyCustomType> as a "Return Type" for a UML Interface Property

In my Visio 2007 UML document I am unable to figure out how I can add an operation to an Interface that returns a generic List<MyCustomType> type.
For example:
Say I have a class named "MyClass" and an Interface named "IFace". IFace has a signature of a method that returns a Generic List of MyClass.
For clarity, here's an example of the C# code:
namespace StackO
{
public interface IFace
{
List<MyClass> SomeMethod(string data);
}
public class MyClass
{
}
}
Here's a screenshot of where I'm stuck:
It seems as though the only way to specify a List<MyClass> as my Return Type is to create another user-defined datatype that is explicitly written as List<MyClass>. If this is the case, so be it. However, I'm posting this in hopes that there is a better/proper way to do this.
How can I define the Return Type of an Operation of a Visio Interface to be a Generic List of a User-Defined Datatype?
In the Class diagram properties > Go to operations > select the return type you are interested in changing and click properties.
In the next dialog you will have option for setting prefix List< and suffix >.
This way you can specify the return type as List<>.
I see this option in Visio 2010. But I am not sure if this option is available in Visio 2007.
There is no such a thing as T1<T2> in UML class diagrams.
If you want to specify that the method returns several values, the correct notation is:
SomeMethod(data: String) : MyClass [*]
This notation is much more powerful than the one used by C#. List<MyClass> SomeMethod(string data) gives no information about the contract of the method. With UML, you know that in:
SomeMethod(data: String) : MyClass [*]
SomethingElse() : String [1..*]
LastExample(number: UnlimitedNatural) : Integer [0..1]
SomeMethod returns a sequence containing zero or more elements. SomethingElse returns a sequence of one or several elements: this sequence is never empty. Finally, LastExample returns an optional value. This could be expressed in C# as int? LastExample(uint number) — see, no IEnumerable here.
Also note that:
SomeMethod(data: String) : MyClass [0..*]
shouldn't be used, since [*] means the same thing and is shorter. As for:
SomeMethod(data: String) : MyClass [0..n]
is incorrect, despite being used a lot on the internet.

When do I have to specify type <T> for IEnumerable extension methods?

I'm a bit confused about the use of all the IEnumerable<T> extension methods, intellisense is always asking for <T>, but I don't think it's necessary to specify <T> at all times.
Let's say I have the following:
List<Person> people = GetSomePeople();
How is this:
List<string> names = people.ConvertAll<string>(p=>p.Name).Distinct<string>().ToList<string>();
different from this:
List<string> names = people.ConvertAll<string>(p=>p.Name).Distinct().ToList();
I think the two lines of code above are sxactly the same, now the question:
How do I know when to specify <T> and when to skip it?
The simplest way is obviously to omit it and see if it compiles.
In practice, you can omit type parameters wherever they are inferred; and they can normally be inferred when they are used in the type of a method parameter than you specify. They cannot be inferred if they're used only in the return type of the method. Thus, for example, for Enumerable.Select<T>, T will be inferred from the type of first argument (which is of type IEnumerable<T>). But for Enumerable.Empty<T>(), will not be inferred, because it's only used in return type of the method, and not in any arguments (as there are none).
Note that the actual rules are more complex than that, and not all arguments are inferable. Say you have this method:
void Foo<T>(Func<T, T> x);
and you try to call it with a lambda:
Foo(x => x);
Even though T is used in type of argument here, there's no way to infer the type - since there are no type specifications in the lambda either! As far as compiler is concerned, T is the same type x is, and x is of type T...
On the other hand, this will work:
Foo((int x) => x);
since now there is sufficient type information to infer everything. Or you could do it the other way:
Foo<int>(x => x);
The specific step-by-step rules for inference are in fact fairly complicated, and you'd be best off reading the primary source here - which is C# language specification.
This feature is known as type inference. In your example, the compiler can automatically determine the generic argument type implicitly for you because in the method call to ConvertAll, the parameter lambda returns a string value (i.e. Name). So you can even remove the <string> part of ConvertAll call. The same is with Distict(), as ConvertAll returns a List<string> and the compiler can declare the generic argument for you.
As for you answer, when the compiler can determine the type itself, the generic argument is redundant and unnecessary. Most of the times, the only place where you need to pass the generic argument is the declaration, like, List<string> list = new List<string>();. You can substitute the first List<string> with var instead or when you are using templates as parameters in lambdas too.