Self-Regular Duck Seal

I want to write a function that works with any value that can be added to other members of its type (regardless of what “added” means in context). The obvious (hehe) definition of this type:

type Addable = { def +(a : Addable) : Addable } 

This gives me an error, I don’t understand at all: recursive method + need result type

Why not the last : Addable result type? Why does he think + recursive?

But I found a more general problem trying to refer to the type inside my own definition:

 type T = { def f: T } 

But then I had a brain wave: solve it the way I would in Java!

 type T[T] = { def f: T } 

Compiled!

But now I have two more problems.

Firstly, I have no idea how to use type T. In particular,

 def n(a:T) = af 

gives a completely understandable, but unpleasant type T error accepts type parameters.

Secondly, trying to apply this pattern to the original problem

 type Addable[Addable] = { def +(a : Addable) : Addable } 

leads to completely incomprehensible "The type of a parameter in a structural refinement cannot relate to an abstract type defined outside this refinement." (The actual problem is not that it is “+” - thank God and Martin, since it will end up ruining my head - it’s just that you need to add it as a parameter).

So,

  • How to determine the value of the duck type type "has a specific function that returns a value of the same type"?
  • How to determine the type of duck? "has a specific function expressing the same type as the parameter"?

I have a religious belief that this problem is solvable.

+4
source share
1 answer

These are different Ts.

 scala> type T[T] = { def f: T } defined type alias T scala> var x: T[Int] = null x: T[Int] = null scala> x = new AnyRef { def f = 5 } x: T[Int] = $anon$1@44daa9f1 

When you write:

 type Addable[Addable] = { def +(a : Addable) : Addable } 

You have an Addable type that accepts a parameter of the same type, also called Addable. Here, similar people often confuse themselves.

 scala> def f[Int](x: Int) = x * x <console>:7: error: value * is not a member of type parameter Int def f[Int](x: Int) = x * x ^ 

The actual answer to your question is “you cannot,” but I would not want to destroy your believing faith, so instead I will say that “structural types work in a mysterious way”. If you want to go on a religious mission, you can visit here, which explains why you cannot.

http://article.gmane.org/gmane.comp.lang.scala/7013

+13
source

All Articles