Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between Seq and Set in Scala

Tags:

set

scala

seq

var seq = Seq[String]()
seq = seq :+ "hello"

var set = Set[String]()
set += "hello"

what's the difference between Seq and Set?

like image 515
Crawford Wilde Avatar asked Nov 06 '13 02:11

Crawford Wilde


2 Answers

Seq

http://www.scala-lang.org/api/current/scala/collection/Seq.html

Sequences always have a defined order of elements. Sequences provide a method apply for indexing.

Seq is similar to java.util.List.

Set

http://www.scala-lang.org/api/current/scala/collection/Set.html

A set is a collection that contains no duplicate elements.

This closely resembles a "set" in the mathematical sense: http://en.wikipedia.org/wiki/Set_(mathematics)

Set is similar to java.util.Set.

like image 90
Chris Martin Avatar answered Sep 28 '22 01:09

Chris Martin


This is described in many places, such as the documentation for Seq and Set and Scala's Collection Library guide.

One could also describe them by their characteristic functions:

  • A Set[A] is a function A => Boolean, which means one can check whether an element is present on it or not.

  • A Seq[A] is a function Int => A, which means that each element in it has an index, and one can retrieve the element that is at any given index.

This also explains the difference between the two statements:

seq = seq :+ "hello"
seq = "hello" +: seq 

set = set + "hello"

On a Set, one doesn't control the ordering of elements, so you simply add elements to it. On a Seq, because each element has an index, it is relevant where the element is being placed, and so we have +: and :+, which specify, respectively, that an element is to be prepended or appended to the sequence.

like image 35
Daniel C. Sobral Avatar answered Sep 28 '22 01:09

Daniel C. Sobral