2014-11-14 4 views
2

두 스트림을 하나로 병합하는 데 도움이 필요합니다.스칼라에서 스트림 병합

(elem1list1#elem1list2, elem2list1#elem2list2...) 

및 기능 휴식을 스트림 중 하나가 그것을 해결하는 방법을

def mergeStream(a: Stream[A], b: Stream[A]):Stream[A] = 
if (a.isEmpty || b.isEmpty) Nil 
else (a,b) match { 
case(x#::xs, y#::ys) => x#::y 
} 

모든 단서가 비어있는 경우 : 출력은 다음과 같이되어야한다?

답변

1

할 수도 zipStream는 튜플에서 그들을 더 이상 Stream 절단 및 flatMap 것이다, 함께 S :

a.zip(b).flatMap { case (a, b) => Stream(a, b) } 

을 나는 그것을 효율성의에 말할 수는 없지만.

scala> val a = Stream(1,2,3,4) 
a: scala.collection.immutable.Stream[Int] = Stream(1, ?) 

scala> val b = Stream.from(3) 
b: scala.collection.immutable.Stream[Int] = Stream(3, ?) 

scala> val c = a.zip(b).flatMap { case (a, b) => Stream(a, b) }.take(10).toList 
c: List[Int] = List(1, 3, 2, 4, 3, 5, 4, 6) 
1
def mergeStream(s1: Stream[Int], s2: Stream[Int]): Stream[Int] = (s1, s2) match { 
    case (x#::xs, y#::ys) => x #:: y #:: mergeStream(xs, ys) 
    case _ => Stream.empty 
} 

scala> mergeStream(Stream.from(1), Stream.from(100)).take(10).toList 
res0: List[Int] = List(1, 100, 2, 101, 3, 102, 4, 103, 5, 104) 
1

당신은 scalaz에서 인터리브 사용할 수 있습니다

scala> (Stream(1,2) interleave Stream.from(10)).take(10).force 
res1: scala.collection.immutable.Stream[Int] = Stream(1, 10, 2, 11, 12, 13, 14, 15, 16, 17)