代码之家  ›  专栏  ›  技术社区  ›  Teja Kantamneni

什么是Scala查找数组中所有元素是否具有相同长度的方法?

  •  10
  • Teja Kantamneni  · 技术社区  · 16 年前

    我是Scala新手,但对Java非常熟悉,对使用FP语言如“Haskell”有一定的了解。

    def checkLength(vals: Array[String]): Boolean = {
      var len = -1
      for(x <- conts){
        if(len < 0)
          len = x.length()
        else{
          if (x.length() != len)
            return false
          else
            len = x.length()
        }
      }
      return true;
    }
    

    7 回复  |  直到 16 年前
        1
  •  21
  •   oxbow_lakes    16 年前
    list.forall( str => str.size == list(0).size )
    

    编辑:这是一个尽可能通用的定义,还允许检查除长度以外的属性是否对所有元素都相同:

    def allElementsTheSame[T,U](f: T => U)(list: Seq[T]) = {
        val first: Option[U] = list.headOption.map( f(_) )
        list.forall( f(_) == first.get ) //safe to use get here!
    }
    
    type HasSize = { val size: Int }
    val checkLength = allElementsTheSame((x: HasSize) => x.size)_
    
    checkLength(Array( "123", "456") )
    
    checkLength(List( List(1,2), List(3,4) ))
    
        2
  •  7
  •   Daniel C. Sobral    16 年前

    def checkLength(vals: Array[String]): Boolean = vals.map(_.length).removeDuplicates.size <= 1
    

    请注意 removeDuplicates 可能会被命名为 distinct 在Scala 2.8上。

        3
  •  3
  •   Dario    16 年前

    提示:使用 forall 确定集合中的所有元素是否满足某个谓词(例如长度相等)。

        4
  •  2
  •   Rex Kerr    16 年前

    list match {
      case x :: rest => rest forall (_.size == x.size)
      case _ => true
    }
    

    现在长度为零的列表返回true,而不是抛出异常。

        5
  •  2
  •   Israel Unterman    11 年前
    list.groupBy{_.length}.size == 1
    

    将列表转换为等长字符串组的映射。如果所有字符串的长度相同,则映射将只包含一个这样的组。

    这个解决方案的好处是,您不需要知道字符串长度的任何信息,也不需要将它们压缩到第一个字符串。它在空字符串上运行良好,在这种情况下返回false(如果这是您想要的…)

        6
  •  1
  •   Germán    16 年前

    def check(list:List[String]) = list.foldLeft(true)(_ && list.head.length == _.length)
    
        7
  •  0
  •   Duncan McGregor Evgeniy Dorofeev    14 年前

    就我的0.02

    def allElementsEval[T, U](f: T => U)(xs: Iterable[T]) =
      if (xs.isEmpty) true
      else {
        val first = f(xs.head)
        xs forall { f(_) == first }
      }
    

    Iterable ,计算f的次数为可能的最小次数,当块不能被转换时,类型推断器可以推断块参数类型。

      "allElementsEval" should "return true for an empty Iterable" in {
        allElementsEval(List[String]()){ x => x.size } should be (true)
      }
      it should "eval the function at each item" in {
        allElementsEval(List("aa", "bb", "cc")) { x => x.size } should be (true)
        allElementsEval(List("aa", "bb", "ccc")) { x => x.size } should be (false)
      }
      it should "work on Vector and Array as well" in {
        allElementsEval(Vector("aa", "bb", "cc")) { x => x.size } should be (true)
        allElementsEval(Vector("aa", "bb", "ccc")) { x => x.size } should be (false)
        allElementsEval(Array("aa", "bb", "cc")) { x => x.size } should be (true)
        allElementsEval(Array("aa", "bb", "ccc")) { x => x.size } should be (false)
      }
    

    可惜的是 head :: tail 对于Iterables来说,模式匹配失败得如此隐晦。

    推荐文章