def convert(list: List[String]): Seq[Either[String, Int]] = list match {
case head :: Nil => Right(head.toInt) :: Nil;
case head :: tail => Right(head.toInt) :: convert(tail) :: Nil;
}
print(convert(List("3", "4", "55")))
我需要一个seq的任何一个,但它转换成一个列表[equlals],我不知道该怎么做。
答案 0 :(得分:1)
如果您想将List[String]
转换为Seq[Either[String,Int]]
。
val input = List("1", "2", "testString")
//input: List[String] = List(1, 2, testString)
转换:
import scala.util.Try
val output: Seq[Either[String,Int]] =
input.map(ele => Try(Right(ele.toInt)).getOrElse(Left(ele))).toSeq
//output: Seq[Either[String,Int]] = List(Right(1), Right(2), Left(testString))
答案 1 :(得分:0)
解决方案:
def convert(list: List[String]): Seq[Either[String, Int]] = list match {
case head :: Nil => Right(head.toInt) +: Seq.empty;
case head :: tail => Right(head.toInt) +: convert(tail);
}
答案 2 :(得分:0)
我非常喜欢Rumeshs解决方案,但如果您更喜欢模式匹配样式:
def convert (list: List [String]): List [Either [String, Int]] = list match {
case Nil => Nil
case head :: tail => if (head.matches ("[0-9]+"))
Right (head.toInt) :: convert (tail) else
Left (head) +: convert (tail)
}
convert (List("3", "four", "55"))
// res304: List[scala.util.Either[String,Int]] = List(Right(3), Left(four), Right(55))
convert (List("3", "4", "55"))
// res305: List[scala.util.Either[String,Int]] = List(Right(3), Right(4), Right(55))
最终将它转换为Seq很容易
convert (List("3", "4", "55")).toSeq
或者使用你自己的+ :)方法,然而它会返回一个List,因为List是一个Seq,但它在失败的.toInt调用时错过了。
我没有测试它 - 也许这个解决方案比Try {}方法更快,可能更慢,可能取决于与int的匹配失败的频率。
Rumesh指出,list.map可以同时工作,所以这里是String方式中的Pattern匹配方法:
List("3", "four", "55") .map (ele =>
if (ele.matches ("[0-9]+")) Right (ele.toInt) else (Left(ele))).toSeq
// res307: scala.collection.immutable.Seq[Product with Serializable with scala.util.Either[String,Int]] = List(Right(3), Left(four), Right(55))
List("3", "4", "55") .map (ele =>
if (ele.matches ("[0-9]+")) Right (ele.toInt) else (Left(ele))).toSeq
// res308: scala.collection.immutable.Seq[Product with Serializable with scala.util.Either[String,Int]] = List(Right(3), Right(4), Right(55))