scala - Self-referential duck-typing -


i wish write function operates on value can added other members of own type (whatever "added" means in context). obvious (heh-heh) definition of such type:

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

that gives me error don't understand @ all: recursive method + needs result type

why isn't last : addable result type? why think + recursive anyway?

but found more general problem, trying refer type inside own definition:

type t = { def f: t  }      

but had brain-wave: solve way in java!

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

this compiled!

but have 2 more problems.

first, have no idea how use type t. in particular,

def n(a:t) = a.f 

gives wholly sensible yet frustrating "type t takes type parameters" error.

second, attempting apply pattern original problem

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

leads incomprehensible "parameter type in structural refinement may not refer abstract type defined outside refinement". (the actual problem not it's "+" -- thank god , martin, since complete mess head -- takes addable parameter.)

so

  1. how define duck-type meaning "has particular function returning value of same type"?
  2. how define duck-type meaning "has particular function taking expression of same type parameter"?

i have religious-like belief problem solvable.

those 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 write:

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

you have type addable takes single type parameter, called addable. here's similar variation people confuse with.

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

the actual answer question "you can't" hate shatter religious-like faith instead i'll "structural types work in mysterious ways." if want go on religious mission might visit here, explains why can't.

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


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -