Skip to content

Instantly share code, notes, and snippets.

@lambda-hacker
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lambda-hacker/c65c53fe17f8474dfdba to your computer and use it in GitHub Desktop.
Save lambda-hacker/c65c53fe17f8474dfdba to your computer and use it in GitHub Desktop.
zip exercises [Scala]
// zip3 Lists
object ZipUtils {
def zip3[A, B, C] (xs: List[A], ys: List[B], zs: List[C]) : List[(A, B, C)] = {
def zip3_aux(xs: List[A], ys: List[B], zs: List[C],
acc: List[(A, B, C)]) : List[(A, B, C)] = (xs, ys, zs) match {
case (Nil, _, _) |
(_, Nil, _) |
(_, _, Nil) => acc
case (xh::xt, yh::yt, zh::zt) => zip3_aux (xt, yt, zt, (xh, yh, zh) :: acc )
}
zip3_aux(xs, ys, zs, Nil).reverse
}
def zipWith [A, B] (f: (A, B) => Any) (xs: List[A], ys: List[B]) : List[Any] = {
xs zip ys map { case (x, y) => f(x, y) }
}
// zip3 Vectors
def zip3[A, B, C] (xs: Vector[A], ys: Vector[B], zs: Vector[C]) : Vector[(A, B, C)] = {
val l = xs.length min ys.length min zs.length
def zipaux (v: Int, acc: Vector[(A, B, C)]) : Vector[(A, B, C)] =
if (v == 0) acc
else zipaux(v - 1, acc :+ ( xs(l - v), ys(l - v), zs(l - v) ))
zipaux (l, Vector.empty)
}
def zip3Vec[A, B, C] (xs: Vector[A], ys: Vector[B], zs: Vector[C]) : Vector[(A, B, C)] = {
val l = xs.length min ys.length min zs.length
(0 to l-1).toVector.map(i => (xs(i), ys(i), zs(i)))
}
}
@tabrez
Copy link

tabrez commented Feb 10, 2015

https://gist.github.com/tabrez/b86bb73baf2dde24b7c5

Try to write zip3 using higher-order functions without worrying about efficiency. Add some example calls to these methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment