[英]Scala equivalent to Haskell's transpose
If to exactly line-by-line translate this form of Haskell's transpose function to Scala, what it would be?如果将这种形式的 Haskell 转置函数精确地逐行转换为 Scala,它会是什么?
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:我对 Scala 的尝试不起作用:
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. Scala和haskell有点不一样,这里的模式匹配比起haskell也有点欠缺。 Also, since Scala has a mix of ObjectOriented components,
head
and tail
are methods
defined on List
objects
and not pure functions
.此外,由于 Scala 混合了面向对象的组件,因此
head
和tail
是定义在List
objects
上的methods
,而不是纯functions
。 You will have to replace map head xss
by scala equivalent xss.map(_.head)
.您将不得不用 Scala 等效
xss.map(_.head)
替换map head xss
。
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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.