0

我在尝试将我制作的压缩列表合并到案例类中时遇到问题。我对 Scala 相当陌生,似乎无法解决这个问题。这是我到目前为止所拥有的:

type Name = String
type Number = String
type Mark = Int
type Rank = Int
type Nationality = String
val Ran = new scala.util.Random

case class Student(name:Name, id: Number, nat:Nationality)
case class StExam(name:Name,id:Number)
case class StMark(id:Number, mark:Mark)
case class Result(name:Name, mark:Mark, rank:Rank)

这些是预定义的类型和案例类。

def marks(ls:List[String]):List[StMark] = {
  val r = new scala.util.Random
  val k = 1 to 20 map { _ => r.nextInt(100) } 
  k.toList
    val f = ls.zip(k)
    f.toList
    val l:List[StMark] = f
    l.sortBy(x => x.mark)
}

这是我写的函数。我想做的是接受一个字符串类型的列表,创建一个随机数列表,然后将这两个列表合并为案例类的一部分StMark

4

1 回答 1

1

type给你正在做的事情起别名是一个非常糟糕的主意。对于默认值坚持默认值。

object Test {
  val Ran = new scala.util.Random

  case class Student(name: String, id: String, nat: String)
  case class StExam(name: String, id: String)
  case class StMark(id: String, mark: Int)

  object StMark {
    def apply(tp: (String, Int)): StMark = StMark(tp._1, tp._2)
  }
  case class Result(name: String, mark: Int, rank: Int)

  def marks(ls: List[String]): List[StMark] = {
    val r = new scala.util.Random
    val k = 1 to 20 map { _ => r.nextInt(100) } toList
    val f = ls.zip(k).toList map { (x: (String, Int)) => StMark(x) }
    f.sortBy(_.mark)
  }
}

你遗漏了一些东西,你的toList操作没有执行到位。

f.toList // returns a new object, it is not updating f itself.
// it's useless in your current code.
于 2013-11-10T15:53:00.380 回答