typestar

String processing in OCaml

split_on_char and filter_map turn field notes into data.

(* 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)

How it works

  1. String.split_on_char ';' breaks the note into entries.
  2. List.filter_map parse converts and drops failures at once.
  3. String.exists asks a character-level question.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
492
Tokens
113
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 113 seconds.

Type this snippet

Step 4 of 4 in Collections, step 21 of 29 in Language basics.

← Previous Next →