Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] python-style array access
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Yaron M. Minsky <yminsky@C...>
Subject: [Caml-list] python-style array access
One of the things I miss from Python is the small syntactical touches that
simplify common operations.  one of my favorites is the way python does
array indexing.  You can use negative numbers to count from the end of the
array, and you can easily take subranges of arrays or strings.  It's
actually quite simple to get the same functionality in ocaml, and here's
some simple code for doing it.  It adds a bit of overhead (an extra
function call), but where that small overhead isn't an issue, I think this
is a nice solution.  If you include the following code in the beginning of
your module, you'll be able to do the following kind of tricks:

# "foobar".[-1];;
- : char = 'r'
# "foobar".[-2];;
- : char = 'a'
# String.rsub "foobar" 0 (-1);;
- : string = "fooba"
# String.rsub "foobar" 1 0;;
- : string = "oobar"
# String.rsub "foobar" 1 3;;
- : string = "oo"
# String.rsub "foobar" 1 (-1);;
- : string = "ooba"

The same kind of things can be done with arrays.  rsub stans for "range
sub", by the way.  Note that a 0 in the second position of rsub means the
very last as opposed to the very first index position.

------ Snip Here -------

open StdLabels
open MoreLabels

module Array =
  include Array
  let normalize ar i = if i < 0 then length ar + i else i
  let get ar i = get ar (normalize ar i)
  let rsub ar start stop =
    let stop = if stop = 0 then length ar else stop in
    let pos = normalize ar start in
    let len = (normalize ar stop) - pos in
    sub ar ~pos ~len

module String =
  include String
  let normalize str i = if i < 0 then length str + i else i
  let get str i = get str (normalize str i)
  let rsub str start stop =
    let stop = if stop = 0 then length str else stop in
    let pos = normalize str start in
    let len = (normalize str stop) - pos in
    sub str ~pos ~len

|--------/            Yaron M. Minsky              \--------|
|--------\ /--------|

Open PGP --- KeyID B1FFD916 (new key as of Dec 4th)
Fingerprint: 5BF6 83E1 0CE3 1043 95D8 F8D5 9F12 B3A9 B1FF D916

To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: