typestar

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

  1. val tideHeights: List[Int] = List(4, 7, 11, 9, 3) es un literal de lista con cinco lecturas en el orden escrito.
  2. 2 :: tideHeights agrega al frente, tideHeights :+ 5 al final; ambos dan listas nuevas y la original no cambia.
  3. withDawn.head es la primera lectura y .tail el resto; .headOption da un Option[Int] donde head lanzaría.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 1 de 3 en Colecciones; paso 10 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →