(********************************************************************)
(*  OCaml code from the book ``Learn Programming with OCaml''       *)
(*  See https://usr.lmf.cnrs.fr/lpo/                                *)
(*                                                                  *)
(*  Sylvain Conchon and Jean-Christophe Filliâtre                   *)
(*  Copyright 2025 Université Paris-Saclay and CNRS                 *)
(*                                                                  *)
(*  Openly licensed via CC BY SA 4.0                                *)
(*  See https://creativecommons.org/licenses/by-sa/4.0/deed.en      *)
(********************************************************************)

(* Program 28 on page 192
   Subrope Extraction *)

  let rec mksub start stop t =
    if start = 0 && stop = length t then
      t
    else match t with
      | Str (s, ofs, _) ->
          Str (s, ofs+start, stop-start)
      | App (t1, t2, _) ->
          let n1 = length t1 in
          if stop <= n1 then mksub start stop t1
          else if start >= n1 then mksub (start-n1) (stop-n1) t2
          else mksub start n1 t1 ++ mksub 0 (stop-n1) t2

  let sub t ofs len =
    let stop = ofs + len in
    if ofs < 0 || len < 0 || stop > length t then invalid_arg "sub";
    if len = 0 then empty else mksub ofs stop t

This document was generated using caml2html