How in Scala to find unique items in List

前端 未结 8 925
既然无缘
既然无缘 2020-12-04 17:14

How in Scala to find unique items in List?

8条回答
  •  感情败类
    2020-12-04 17:52

    The most efficient order-preserving way of doing this would be to use a Set as an ancillary data structure:

    def unique[A](ls: List[A]) = {
      def loop(set: Set[A], ls: List[A]): List[A] = ls match {
        case hd :: tail if set contains hd => loop(set, tail)
        case hd :: tail => hd :: loop(set + hd, tail)
        case Nil => Nil
      }
    
      loop(Set(), ls)
    }
    

    We can wrap this in some nicer syntax using an implicit conversion:

    implicit def listToSyntax[A](ls: List[A]) = new {
      def unique = unique(ls)
    }
    
    List(1, 1, 2, 3, 4, 5, 4).unique    // => List(1, 2, 3, 4, 5)
    

提交回复
热议问题