我创建了MyList抽象类来实现列表,不使用现有列表实现的原因是我正在学习 Scala,这是同一门课程的练习。我正在编写一个zipWith函数来创建一个包含单个项目串联的新列表,例如:
列表 1:列表 =[1,2,3]
列表 2:listOfStrings =["Hello", "This is", "Scala"]
我期待这样的输出:[1-Hello, 2-This is, 3-Scala]
我编写了zipWith如下函数:
override def zipWith[B, C](list: MyList[B], zip: (A, B) => C): MyList[C] = {
if(list.isEmpty) throw new RuntimeException("Lists do not have the same length")
else new Cons(zip(h, list.head), t.zipWith(list.tail, zip))
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下语句调用此函数:
println(list.zipWith[String, String](listOfStrings, (Int,String)=>_+"-"+_))
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
我无法推断扩展函数的参数 $3 的类型:( $3, _$4) => _$3 + "-" + _$4。
明确提到了此变量的类型,因为Int我仍然收到此错误。这可以使用以下方法解决:
println(list.zipWith[String, String](listOfStrings, _+"-"+_))
Run Code Online (Sandbox Code Playgroud)
我无法理解为什么早期的语句失败,即使在给出所需变量的类型之后也是如此
我有一个具有以下案例类类型的数据集:
case class AddressRawData(
addressId: String,
customerId: String,
address: String
)
Run Code Online (Sandbox Code Playgroud)
我想将其转换为:
case class AddressData(
addressId: String,
customerId: String,
address: String,
number: Option[Int], //i.e. it is optional
road: Option[String],
city: Option[String],
country: Option[String]
)
Run Code Online (Sandbox Code Playgroud)
使用解析器函数:
def addressParser(unparsedAddress: Seq[AddressData]): Seq[AddressData] = {
unparsedAddress.map(address => {
val split = address.address.split(", ")
address.copy(
number = Some(split(0).toInt),
road = Some(split(1)),
city = Some(split(2)),
country = Some(split(3))
)
}
)
}
Run Code Online (Sandbox Code Playgroud)
我是 Scala 和 Spark 的新手。谁能告诉我如何做到这一点?