typestar

Procesar strings en OCaml

split_on_char y filter_map vuelven datos las notas de campo.

(* String.split_on_char and friends handle field notes. *)
let notes = "limpet,40;anemone,12;sea star,3"

let parse entry =
  match String.split_on_char ',' entry with
  | [species; n] -> Some (species, int_of_string n)
  | _ -> None

let () =
  notes
  |> String.split_on_char ';'
  |> List.filter_map parse
  |> List.iter (fun (s, n) -> Printf.printf "%-9s %3d\n" s n);
  Printf.printf "Note length: %d chars\n" (String.length notes);
  Printf.printf "Has star? %b\n"
    (String.exists (fun c -> c = '*') notes)

Cómo funciona

  1. String.split_on_char ';' parte la nota en entradas.
  2. List.filter_map parse convierte y bota fallos a la vez.
  3. String.exists hace una pregunta a nivel de caracteres.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
16
Caracteres a escribir
492
Tokens
113
Ritmo de tres estrellas
60 tpm

Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 113 segundos.

Escribe este fragmento

Paso 4 de 4 en Colecciones; paso 21 de 29 en Fundamentos del lenguaje.

← Anterior Siguiente →