Scala相当于Haskell的转置

时间:2018-11-06 03:07:08

标签: scala

如果要准确地逐行将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)

我尝试使用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)
}

经过翻译地图功能的困扰后,这作为最后一行也不起作用:

case (x::xs)::xss => (x:: xss.map(head xss)) :: scalaTranspose(xs :: xss.map(tail xss))

1 个答案:

答案 0 :(得分:1)

Scala与haskell有点不同,与haskell相比,这里的模式匹配也有些不足。另外,由于Scala混合了面向对象的组件,因此from django.conf import settings from django.core.mail import send_mail send_mail('This is the title of the email', 'This is the message you want to send', settings.DEFAULT_FROM_EMAIL, [ settings.EMAIL_HOST_USER, # add more emails to this list of you want to ] ) head是在tail methods上定义的List而非纯objects上。您将必须用等同于scala的functions替换map head xss

xss.map(_.head)