If to exactly line-by-line translate this form of Haskell's transpose function to Scala, what it would be?
Haskell's transpose:
tr :: [[a]] -> [[a]]
tr [] = []
tr ([] : xss) = tr xss
tr ((x:xs) : xss) = (x : map head xss) : tr (xs : map tail xss)
My attempt for Scala does not work:
def scalaTranspose(m: List[List[Int]]): List[List[Int]] = m match {
case Nil => Nil
case Nil::xss => scalaTranspose(xss)
case (x::xs)::xss => (x:: map head xss) :: scalaTranspose(xs :: map tail xss)
}
After struggling with translating map function, this as a last line also doesn't work:
case (x::xs)::xss => (x:: xss.map(head xss)) :: scalaTranspose(xs :: xss.map(tail xss))
Scala is a bit different from haskell, and the pattern matching here is also a bit lacking compared to haskell. Also, since Scala has a mix of ObjectOriented components, head
and tail
are methods
defined on List
objects
and not pure functions
. You will have to replace map head xss
by scala equivalent xss.map(_.head)
.
def scalaTranspose(m: List[List[Int]]): List[List[Int]] = m match {
case Nil => Nil
case Nil :: xss => scalaTranspose(xss)
case (x :: xs) :: xss => (x :: xss.map(_.head)) :: scalaTranspose(xs :: xss.map(_.tail))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.