How to implement an F# interface with a member returing an instance of that interface? - interface

Let's say I have the following interface in F#:
type InterfaceA =
abstract Magic : InterfaceA -> InterfaceA
How can I implement such interface?
When I try to do it like this:
type MyTypeA = {x:int} with
interface InterfaceA with
member self.Magic another =
{x=self.x+another.x}
I get the error:
This expression was expected to have type 'InterfaceA' but here has type 'MyTypeA'

To fix the type error, you need to explicitly cast the returned value to the InterfaceA type - unlike for example C#, F# does not do this automatically:
type InterfaceA =
abstract Magic : InterfaceA -> InterfaceA
abstract Value : int
type MyTypeA =
{x:int}
interface InterfaceA with
member self.Value = self.x
member self.Magic another =
{ x=self.x+another.Value } :> InterfaceA
Note that your code also did not work because another was of type InterfaceA and so it did not have the x field you could access. To fix this, I added a member Value to the interface.

Posting as an alternative that's not really better, just different:
As of F# 6, you can also annotate the return type and the compiler will infer what you mean:
type InterfaceA =
abstract Magic : InterfaceA -> InterfaceA
abstract Value : int
type MyTypeA =
{x:int}
interface InterfaceA with
member self.Value = self.x
member self.Magic another : InterfaceA =
{ x=self.x+another.Value }

Related

Dart - Limit generic constrained type to sub type

i am currently working with Flutter/Dart. I want to implement a generic helper class, which puts a received input value into a generic wrapper, depending on the type.
Here the example code:
class ClassA {}
class ClassB<T> {
ClassB(this.t);
final T t;
}
class ClassC<T extends ClassA? {
ClassC(this.t);
final T t;
}
class ClassD<T> {
ClassD(this.t);
final T t;
Object getWrapper(){
final t = this.t;
return T == ClassA?
? ClassC<T>(t) //<--fails
: ClassB<T>(t);
}
}
Produces:
'T' doesn't conform to the bound 'ClassA?' of the type parameter 'T'.
ClassD is the helper which produces the wrappers. For the wrapper ClassB there is no isdue, but i could not get it to work for the wrapper ClassC. As it constrains its generic type it conflicts with the generic type of the wrapper itself, although i also included a type check there to limit the type to the constrained one.
I am wondering why this won't work and how it could be adjusted to make it work.
I tried to add a type check and adjusted it in various ways like
T == ClassA
or
T is ClassA
also including the local variable t
T == ClassA && t is ClassA

Generics in TypeScript: How to infer the type of an instance from the class

A factory function creates the instances of classes:
class A {
name: string
}
function factory<T>(Cl): T {
return new Cl()
}
let a = factory<A>(A)
a.name // OK
I would like to avoid the repetition of A in: factory<A>(A). The generics instance type should be able to be inferred from the class type, shouldn't be?
I tried this code:
function factory<T>(Cl: typeof T): T { // Error: Cannot find name 'T'
return new Cl()
}
Is there a way to do this?
Based on the Typescript documentation :
When creating factories in TypeScript using generics, it is necessary
to refer to class types by their constructor functions.
So you must do something like this:
function factory<T>(Cl: { new(): T; }): T {
return new Cl();
}
In the code above, Cl must a type that at least has a constructor which return T generic type.
So the type inference will work:
let a = factory(A);
a.name;
You don't need to specify the type of A anyway because the compiler know it.

Swift generic Type inheriting from another generic type

I am trying to get the code below working in a playground:
public protocol SomeTypeProtocol {
associatedtype T
func convertTo<TNew:SomeTypeProtocol>()-> TNew
}
public class SomeClass<T>: SomeTypeProtocol{
var item:T
public init(item:T)
{
self.item = item
}
public func convertTo<TNew:SomeTypeProtocol where TNew.T : T>()-> TNew
{
return SomeClass<TNew.T>(item: item as! TNew.T)
}
}
Basically, I have a protocol with an associated type T, and a class conforming to that protocol with generic type T, and I need to implement the convertTo function that simply converts the class's type T to another type TNew.T which should be a subclass from T.
I have this implemented in other languages like C# and Java, so I am not sure why I can't get it working in Swift.
I am getting the following errors:
1) error: type 'TNew.T' constrained to non-protocol type 'T'
public func convertTo<TNew:SomeTypeProtocol where TNew.T : T>()-> TNew
2) error: cannot invoke initializer for type 'SomeClass<TNew.T>' with an argument list of type '(item: TNew.T)'
return SomeClass<TNew.T>(item: item as! TNew.T)
3) note: expected an argument list of type '(item: T)'
return SomeClass<TNew.T>(item: item as! TNew.T)
4)note: protocol requires nested type 'T'
associatedtype T
TNew.T : T
This is where the problem lies.
The colon, :, is used to declare a conformance constraint, not equality. You need to rewrite this as TNew.T == T if you want to equate the two types TNew.T and T.
I believe the closest you can get to doing something like that is this:
public func convertTo<TNew where TNew : T>()-> SomeClass<TNew>
{
return SomeClass<TNew>(item: item as! TNew)
}
But I don't believe you can't enforce it being only a subclass and not the same class.
Be careful doing this type of thing with generics. If you're needing to constantly change the Type of your generic, you might want to consider using a different design.

Scala generics - why I can't create parametrised object inside generic class?

I'm currently learning scala.
Why this code doesn't work:
class GenClass[T](var d : T) {
var elems: List[T] = Nil
def dosom(x: T) = {
var y = new T()
y
}
}
I get:
error: class type required but T found
in place of var y - new T()
Is it because type erasing from java? Is there any way to solve this - create variable of type T inside generic function?
have a look at this question, there's an example of a factory:
How to instantiate an instance of type represented by type parameter in Scala
Because you can not be sure there always is a public, parameterless constructor.

Define an abstract class that inherits an infterface, but does not implement it

incorporating leppies feedback it compiles - but IMO some drawbacks I want each sub class to be forced by the compiler to define their own Uri property. Code as it is now:
[<AbstractClass>]
type UriUserControl() =
inherit UserControl()
interface IUriProvider with
member this.Uri with get() = null
Interesting enough, the class I defines which inerits from above does not show a public Uri property:
type Page2() as this =
inherit UriUserControl()
let uriStr = "/FSSilverlightApp;component/Page2.xaml"
let mutable uri = new System.Uri(uriStr, System.UriKind.Relative)
do
Application.LoadComponent(this, uri)
member public this.Uri with get () = uri
I would like to define an abstract class that inherits from UserControl and my own Interface IUriProvider, but doesn't implement it. The goal is to be able to define pages (for silverlight) that implement UserControl but also provide their own Uri's (and then stick them in a list / array and deal with them as a set:
type IUriProvider =
interface
abstract member uriString: String ;
abstract member Uri : unit -> System.Uri ;
end
[<AbstractClass>]
type UriUserControl() as this =
inherit IUriProvider with
abstract member uriString: String ;
inherit UserControl()
Also the Uri in the definition - I would like to implement as a property getter - and am having issues with that as well.
this does not compile
type IUriProvider =
interface
abstract member uriString: String with get;
end
Here is a way to do it:
type IUriProvider =
abstract member UriString: string
abstract member Uri : System.Uri
[<AbstractClass>]
type UriUserControl() as this =
inherit System.Windows.Controls.UserControl()
abstract member Uri : System.Uri
abstract member UriString : string
interface IUriProvider with
member x.Uri = this.Uri
member x.UriString = this.UriString
Note that you have to provide an implementation of the interface (since all interface implementations in F# are explicit), but this can just refer back to abstract members in the class. Then you can subclass thusly:
type ConcreteUriUserControl() =
inherit UriUserControl()
override this.Uri = null
override this.UriString = "foo"
From a .NET point of view, you would need to at least provide an abstract implementation for the interface. But that again could proof problematic due to default interface accessibility, which would require some more glue again for an explicit implementation.