scala - Megre two sorted Array, List vs Array -
this function merges 2 sorted lists. takes 2 lists parameter , returns one.
def merge(xs : list[int], ys : list[int]) : list[int] = { (xs, ys) match { case (nil, nil) => nil case (nil, ys) => ys case (xs, nil) => xs case (x :: xs1, y :: ys1) => if(x < y) x :: merge(xs1, ys) else y :: merge(xs, ys1) } }
i wanted rewrite function changing parameter type list array, , did not work. however, going list seq worked. tell me not work arrays?
def mergedontwork(xs : array[int], ys : array[int]) : array[int] = { (xs, ys) match { case (array.empty,array.empty) => array.empty case (array.empty, ys) => ys case (xs, array.empty) => xs case (x +: xs1, y +: ys1) => if(x < y) x +: merge2(xs1, ys) else y +: merge2(xs, ys1) } }
the error comes part of code : if(x < y) x +: merge2(xs1, ys)
: array[any] not conform expected type array[int]
edit
i understood how go list array solutions proposed pedromss , harald. modified function making tail recursive.
def mergetailrecursion(xs : array[int], ys : array[int]) : array[int] ={ def recurse( acc:array[int],xs:array[int],ys:array[int]):array[int]={ (xs, ys) match { case (array(),array()) => acc case (array(), ys) => acc++ys case (xs, array()) => acc++xs case (a@array(x, _*), b@array(y, _*)) => if (x < y) recurse(acc:+x, a.tail, b) else recurse( acc:+y, a, b.tail) } } recurse(array(),xs,ys) }
- you can't pattern match on
array.empty
because method. usearray()
instead. (x +: xs1, y +: ys1)
doesn't appear valid match expression. change(x +: xs1, y +: ys1)
compiling version of code:
object arrays extends app { def merge(xs: array[int], ys: array[int]): array[int] = { (xs, ys) match { case (array(), array()) => array.empty case (array(), ys2) => ys2 case (xs2, array()) => xs2 case (xs1@array(x, _*), ys1@array(y, _*)) => if (x < y) x +: merge(xs1.tail, ys) else y +: merge(xs, ys1.tail) } } merge(array(1, 2, 3), array(4, 5, 6)).foreach(println) }
refer [here|why can't pattern match on stream.empty in scala? explanation pattern matching on methods.
and [here|how pattern match arrays in scala? explanation _*
. match number of arguments.
lastlty xs1@
, [documentation|https://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html]:
pattern binders
pattern2 ::= varid `@' pattern3
a pattern binder xx@pp consists of pattern variable xx , pattern pp. type of variable xx static type tt of pattern pp. pattern matches value vv matched pattern pp, provided run-time type of vv instance of tt, , binds variable name value.
you with
case (array(x, _*), array(y, _*)) => if (x < y) x +: merge(xs.tail, ys) else y +: merge(xs, ys.tail)
Comments
Post a Comment