简体   繁体   English

如何指定元组类型签名

[英]How to specify tuple type signature

I'm working through the "Learning Scala" book and have gotten to this exercise in chapter 4:我正在阅读“Learning Scala”一书,并在第 4 章中完成了这个练习:

Write a function that takes a 3-sized tuple and returns a 6-sized tuple, with each original parameter followed by its String representation.编写一个 function,它接受一个 3 大小的元组并返回一个 6 大小的元组,每个原始参数后跟它的字符串表示形式。 For example, invoking the function with (true, 22.25, "yes") should return (true, "true", 22.5, "22.5", "yes", "yes").例如,使用 (true, 22.25, "yes") 调用 function 应该返回 (true, "true", 22.5, "22.5", "yes", "yes")。

The most promising of my attempts to specify the type signature is this:我尝试指定类型签名的最有希望的是:

def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {

produces these errors:产生这些错误:

Exercises.scala:99: error: not found: type A
  def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
                                        ^
Exercises.scala:99: error: not found: type B
  def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
                                           ^
Exercises.scala:99: error: not found: type C
  def t3ToT6[Tuple3[A, B, C]](t: Tuple3[A, B, C]) = {
                                              ^

The intent is to allow any type, so I though I could indicate those with the A , B , or C ?目的是允许任何类型,所以我虽然可以用ABC指示那些?

If I take away the type specification and just use Tuple3 , then it complains that I should have type params:如果我去掉类型规范而只使用Tuple3 ,那么它会抱怨我应该有类型参数:

Exercises.scala:99: error: type Tuple3 takes type parameters
  def t3ToT6[Tuple3[A, B, C]](t: Tuple3) = {

I suspect I'm close, and this is some sort of syntax issue, but have not yet found any examples of specifying Tuples in type signatures of functions.我怀疑我很接近,这是某种语法问题,但还没有找到在函数的类型签名中指定元组的任何示例。

What is the correct type signature for this problem description?此问题描述的正确类型签名是什么?

Are there examples you know of that I've not yet found which would help me understand this?您是否知道我尚未找到的示例可以帮助我理解这一点?

Identify 3 type parameters like so: [A,B,C]像这样识别 3 个类型参数: [A,B,C]

With this you can...有了这个你可以...

def t3ToT6[A,B,C](t: Tuple3[A,B,C]):Tuple6[A,String,B,String,C,String] =
  Tuple6(t._1, t._1.toString
        ,t._2, t._2.toString
        ,t._3, t._3.toString)

It can also be done with a quick pattern match.也可以通过快速模式匹配来完成。

def t3ToT6[A,B,C](t:(A,B,C)):(A,String,B,String,C,String) = t match {
  case (a,b,c) => (a, a.toString, b, b.toString, c, c.toString)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM