On Tue, 31 Jan 2017 11:35:01 +0000 "Richard W.M. Jones" <rjones@redhat.com> wrote:
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.
That's not entirely true when keep_empty is used in combination with count. When keep_empty is false then the split is not considered a (successful) split and internal state of count is not decreased. Example: # List.filter ((<>) "") (nsplit ~count:3 "," "a,,,b,,,c,,d" ) ;; - : string list = ["a"; "b,,,c,,d"] # nsplit ~keep_empty:false ~count:3 "," "a,,,b,,,c,,d" ;; - : string list = ["a"; "b"; "c"; ",d"]
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
-- Tomáš Golembiovský <tgolembi@redhat.com>