Listas en Scala
Un registro de mareas en una List, extendido por ambos extremos y leído con seguridad.
// a List literal holds its elements in order and never changes
val tideHeights: List[Int] = List(4, 7, 11, 9, 3)
// :: adds to the front and :+ appends to the back, both returning
// a new list rather than editing the old one
val withDawn: List[Int] = 2 :: tideHeights
val withDusk: List[Int] = tideHeights :+ 5
// the original still has its five readings after both operations
val stillFive: Boolean = tideHeights.length == 5
// head is the first element and tail is everything after it
val firstReading: Int = withDawn.head
val laterReadings: List[Int] = withDawn.tail
// head throws on an empty list, so headOption answers with an
// Option instead: Some for a reading, None for no readings at all
val maybeFirst: Option[Int] = List.empty[Int].headOption
val realFirst: Option[Int] = withDusk.headOption
Cómo funciona
val tideHeights: List[Int] = List(4, 7, 11, 9, 3)es un literal de lista con cinco lecturas en el orden escrito.2 :: tideHeightsagrega al frente,tideHeights :+ 5al final; ambos dan listas nuevas y la original no cambia.withDawn.heades la primera lectura y.tailel resto;.headOptionda unOption[Int]dondeheadlanzaría.
Palabras clave y builtins usados aquí
val
El intento, en números
- Líneas
- 19
- Caracteres a escribir
- 811
- Tokens
- 105
- Ritmo de tres estrellas
- 75 tpm
Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 84 segundos.
Paso 1 de 3 en Colecciones; paso 10 de 27 en Fundamentos del lenguaje.