[racket] substring without the copy

From: John Clements (clements at brinckerhoff.org)
Date: Fri Apr 4 16:12:01 EDT 2014

On Apr 3, 2014, at 7:08 PM, Spencer Florence <spencer at florence.io> wrote:

> Is there any way to perform `substring` without creating a new string? I'm working with lots of very large and (for all intents and purposes) immutable strings and would like to avoid the extra allocations and copy time.

Seems like it would be fairly easy to roll this yourself:

#lang racket

(require rackunit)

;; represent a lazy substring operation:
(struct lazysubstring (str start end))

;; force a lazy substring
(define (lss-force s)
  (substring (lazysubstring-str s)
             (lazysubstring-start s)
             (lazysubstring-end s)))

;; get the length of a lazy substring:
(define (lss-len s)
  (- (lazysubstring-end s) (lazysubstring-start s)))

;; create one:
(define source-text "othho tot stnh ontuh .nt")

(define lss1 (lazysubstring source-text 3 9))
(check-equal? (lss-len lss1) 6)

Obviously, you have to “roll your own” for any operation that you want to perform that retains the laziness.


Posted on the users mailing list.