On Mon, Jan 30, 2017 at 10:43:15PM +0100, Tomáš Golembiovský wrote:
Added two new optional arguments to nsplit:
* keep_empty: if set to false empty elements are not stored in the
returned list. The default is to keep the empty elements
The ?keep_empty flag is pointless. It's simpler and more
clear to write:
List.filter ((<>) "") (nsplit ...)
when you don't want empty elements.
However the ?count flag is fine, since that's what Perl's split
function also does.
- let rec nsplit sep str =
+ let rec nsplit ?(keep_empty = true) ?(count = -1) sep str =
let len = length str in
let seplen = length sep in
let i = find str sep in
- if i = -1 then [str]
+ if i = -1 || count = 0 then
+ if str = "" && not keep_empty then [] else [str]
else (
let s' = sub str 0 i in
let s'' = sub str (i+seplen) (len-i-seplen) in
- s' :: nsplit sep s''
+ let elem, count =
+ if s' = "" && not keep_empty then
+ [], count
+ else
+ [s'], if count > 0 then count-1 else count
+ in
+ elem @ nsplit ~keep_empty:keep_empty ~count:count sep s''
You can write this line as:
elem @ nsplit ~count sep s''
(after dropping keep_empty).
Rich.
--
Richard Jones, Virtualization Group, Red Hat
http://people.redhat.com/~rjones
Read my programming and virtualization blog:
http://rwmj.wordpress.com
libguestfs lets you edit virtual machines. Supports shell scripting,
bindings from many languages.
http://libguestfs.org