Hi YCP-Hackers,
I've used some ITO time to implement two new YCP builtins:
1. splitlist (var x, list, block using x)
Takes a list and a predicate function and splits the list where the
predicate function says so. Returns a list of lists.
Example:
list<string> l = [ "0", "a", "1", "2", "b", "3", "4" ];
splitlist(string s, l, { return isalpha(s); });
return is [ [ "0" ], [ "a", "1", "2" ], [ "b", "3", "4" ] ]
The difference to splitstring is that the 'delimiter' is included in the
result since that's the way I need it. If desired I could add a parameter
that tells whether the 'delimiter' should be added to the previous list,
the following list or not at all.
2. reducelist (var x, var y, initial value, list, block using x and y)
This is the standard reduce function known from Lisp (but also available in
e.g. C++, Python and Ruby). It takes a list and reduces it to a single
value by applying a function, see:
http://en.wikipedia.org/wiki/Reduce_%28higher-order_function%29
Examples:
// sum and product
integer sum = reducelist(integer x, integer y, 0, [ 1, 2, 3, 4 ], { return x + y; });
integer product = reducelist(integer x, integer y, 1, [ 1, 2, 3, 4 ], { return x * y; });
// min and max
list<integer> l1 = [ 1, 2, 3 ];
integer min = reducelist(integer x, integer y, l1[0]:nil, l1, { return x < y ? x : y; });
integer max = reducelist(integer x, integer y, l1[0]:nil, l1, { return x > y ? x : y; });
// mergestring
list<string> l2 = [ "hello", "openSUSE", "world" ];
string s = reducelist(string x, string y, "", l2, { return x + " " + y; });
// find longest string
string ls = reducelist(string x, string y, "", l2, { return size(x) > size(y) ? x : y; });
// find length of longest string (note: type of x and y differ)
integer ll = reducelist(integer l, string s, 0, l2, { return size(s) > l ? size(s) : l; });
Patch is attached. Still missing is documentation and testsuite. The patch
contains a binary incompatibility to libycp by adding the clear() function to
YCPList. If that's not wanted a workaround is included (maybe someone has a
better workaround). Bytecode compatibility is not touched.
It's not possible to add the functions to a module since they use the variable
type feature of YCP.
Please comment.
ciao
Arvin
--
Arvin Schnell,