scala - pattern match component 'x' is constrained to be isInstanceOf[List[Any]] - but can't treat 'x' as that type on RHS -
to familiar scala lists decided implement flatten
, take list like: list(list(2,4), 22, list(1))
list(2, 4, 22, 1)
.
when attempted run code below
def flatify(xs: list[any]) : list[any] = { xs match { case nil=> { nil } case x::rest if x.isinstanceof[list[any]] => { flatify(x):: flatify(rest) // bad line } case x::rest => { x:: flatify(rest) } case _ => { throw new illegalstateexception("cant match") } } } var list = list(list(4, 5), 9, 10, list(1, 2)) flatify(list)
the compiler complained line commented '// bad line', saying:
error:(84, 17) type mismatch; found : required: list[any] flatify(x):: flatify(rest) ^
this strikes me odd, since guard condition explicitly requires x
isinstanceof[list[any]]
. understand any
superclass of list[any]
have thought once compiler gets right hand side of expression
flatify(x) :: flatify(rest)
it accept x
list[any]
.
i'm sure implementation might have other problems have not debugged yet, before moved on wanted try understand scala compiler here. tips or pointers gratefully appreciated.
you're matching on list[any]
, when have
case x :: tail if(x.isinstanceof[list[any]]) => x ... ^ ^ ^ true, type of still x determined
x
any
, tail
list[any]
. if
condition nothing change type of x
, if can test x.isinstanceof[list[any]]
, x
still any
. need match on type, itself.
def flatify(xs: list[any]) : list[any] = { xs match { case nil => nil case (x: list[any]) :: rest => flatify(x) ::: flatify(rest) case x :: rest => x :: flatify(rest) case _ => throw new illegalstateexception("cant match") } }
furthermore, there bug. given x
correctly matched list[any]
, following flatify(x) :: flatify(rest)
place list[any]
@ head of list[any]
, , therefore no flattening @ all. changed :::
.
scala> flatify(list(1,2,3,list(4,5,6), list(7,8,9))) res1: list[any] = list(1, 2, 3, 4, 5, 6, 7, 8, 9)