当给定此模式匹配整数值时

当给定此模式匹配整数值时

本文介绍了当给定此模式匹配整数值时,为什么 Scala 会抱怨?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:编写一个函数,生成一个不包括指定字符(由索引标识)的新字符串

Goal: Write a function that generates a new String excluding a specified character (identified by the index)

示例:

  • takeAllExcept(0, "abc") 返回 bc
  • takeAllExcept(1, "abc") 返回 ac
  • takeAllExcept(2, "abc") 返回 ab
  • takeAllExcept(0, "abc") returns bc
  • takeAllExcept(1, "abc") returns ac
  • takeAllExcept(2, "abc") returns ab

我最初做了什么:

def takeAllExcept( index: Int, s: String ): String = {
  val lastIndex = s.length()-1
  index match {
    case 0 => return s.slice(1, s.length)
    case lastIndex => return s.slice(0, s.length()-1)
    case _ => { s.slice(0, index) + s.slice(index+1, s.length) }
  }
}

编译器抱怨 case _ 的语句块无法访问.

The compiler complains that the statement block for case _ is unreachable.

我是如何修复它的

def takeAllExcept( index: Int, s: String ): String = {
  val lastIndex = s.length()-1
  if( index == 0 )
    return s.slice(1, s.length)

  if( index == lastIndex )
    return s.slice(0, s.length()-1)

  s.slice(0, index) + s.slice(index+1, s.length)
}

我想知道为什么我的初始尝试因无法访问的代码而失败.在我看来是合法的.另外,scala 中是否有内置工具可以做到这一点?

I want to know why my initial attempt failed with the unreachable code. It looks legit to me. Also, is there an in-built facility in scala that already does this ?

推荐答案

lastIndex 在模式中是一个新名称的隐式声明,该名称绑定到放入匹配中的任何值并隐藏allready 定义了 lastIndex,正如其他两个帖子 allready 指出的那样.除了使用大写标识符之外,还有另外两种可能性(参见 Peter 的帖子):

lastIndex in the pattern is an implicit declaration of a new name that is bound to whatever value is put into the match and shadows the allready defined lastIndex, as the other two post allready pointed out. There are two other possibilities instead of using upper case identifiers (see Peter's post):

使用反引号让编译器知道这不应是新标识符的声明:

Using backticks to let the compiler know that this shall not be a declaration of a new identifier:

case `lastIndex` => ...

使用模式保护:

case x if x == lastIndex => ...

如果您想对字符串进行大量基于索引的删除,那么通过在字符串上调用 toBuffer 来使用 Buffer 会更快,然后您可以使用 remove(i: Int) Buffer 方法.这仅对一个操作来说较慢,因为您必须在完成后将 Buffer 转换回字符串,但如果您执行许多随机访问操作,速度会快得多.完成后,您可以在缓冲区上调用 mkString 以取回您的字符串.对于单个删除,我会按照 Peter 的建议进行操作,或者这里有一个替代方法:

If you want to do a lot of index-based removing on strings then it would be faster to use a Buffer by calling toBuffer on the string and then you can use the remove(i: Int) method of Buffer. That is slower for only one operation because you will have to convert the Buffer back to string when your done but if you do many random access operations its a lot faster. After your done you can call mkString on the Buffer to get your String back. For single removal I would do it like Peter suggested or here is an alternative:

def takeAllExcept(i: Int, s: String) = s.take(i) + s.drop(i+1)

这篇关于当给定此模式匹配整数值时,为什么 Scala 会抱怨?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:45