Fun type
Methods
- %(x:Any, cb:Fun) Source: stdlib.ngs:1760
Each operator. Same as calling x.each(cb) Example
[1,2,3,4] % echo
- *(cb:Fun, n:Int) Source: stdlib.ngs:7831
Call cb n times without any parameters and accumulate the results. Example
a = Box * 2; a[0] is Box and a[1] is Box and a[0] !== a[1] # true
- +(f:Fun, g:Fun) Source: stdlib.ngs:702
Compose functions Returns
Fun f(g(...))Example
F reject(h:Hash, predicate:Fun) h.filter(not + predicate)
- .(x:Any, f:Fun)EXPERIMENTAL Source: stdlib.ngs:696
Undocumented Automatically called by NGS for syntax
x.{ ... }
Returns
f(x)
- /(x:Any, mapper:Fun) Source: stdlib.ngs:1755
Map operator. Same as calling x.map(mapper) Example
[1,2,3,4] / F(x) x * 10
- ::(x:Any, f:Fun) Source: stdlib.ngs:368
Executes f(x) Returns
x
- =~(x:Any, f:Fun, _mc:MatchContext) Source: stdlib.ngs:1282
Undocumented Returns
f(x).Bool()
- \(x:Any, f:Fun)deprecated Source: stdlib.ngs:1767
Deprecated. Use expr.f() and expr.{ your_code } Call operator. Same as calling f(x) Example
[1,2,3,4] \ echo
- acquire(l:Lock, cb:Fun) Source: stdlib.ngs:2571
Call cb with lock l held. Releases the lock after cb returns or throws. Example
l = Lock() ... l.acquire(F() { modify_global_state_safely(...) })
- all(e:Eachable2, predicate:Fun) Source: stdlib.ngs:3717
Checks whether all of the key-value pairs satisfies the predicate: predicate(k, v) Returns
Bool
- any(e:Eachable2, predicate:Fun) Source: stdlib.ngs:3702
Checks whether any of the key-value pairs satisfies the predicate: predicate(k, v) Returns
Bool
- apply(x:Eachable1, f:Fun) Source: stdlib.ngs:709
Applies f to arguments in x Same as calling f(*x)
- apply(x:Eachable2, f:Fun) Source: stdlib.ngs:716
Applies f to arguments in x Same as calling f(**x)
- assert(f:Fun, t:Type, msg:Str='Assertion failed') Source: stdlib.ngs:334
Throws AssertFail with given function does not throw exception of the given type. Parameters
f Fun t Subtype of Exception Returns
The exceptionExample
assert({1/0}, DivisionByZero)
- block(body:Fun) Source: stdlib.ngs:187
Undocumented Automatically called by NGS for syntax
block NAME BODY
Example
block b { calc(); if answer_found then b.return(42); more_calc(); another_answer }
- cached(cb:Fun) Source: stdlib.ngs:8649
Cache cb results. Runs cb only once. TODO: Support arguments. Returns
New function which wraps cb.Example
my_func = cached( { expensive(); calculation(); steps(); result } ) use_result_of(my_func()) ... use_result_of(my_func())
- collector(al:ArrLike, body:Fun) Source: stdlib.ngs:1931
Defines collector { ... collect(...) ... } behaviour for ArrLike. Very similar to collector for Arr. See collector(Arr,Fun).
- collector(s:Set, body:Fun) Source: stdlib.ngs:2254
Defines collector { ... collect(...) ... } behaviour for Set.
- collector(a:Arr, body:Fun) Source: stdlib.ngs:2751
Defines collector { ... collect(...) ... } behaviour for arrays Parameters
a Initial array body The body after collector keyword and possible initial value, wrapped in a function "collector THIS_CODE" or "collector/my_init THIS_CODE" Returns
Constructed arrayExample
items = collector { collect(10) for(i;2) collect(i) collect(20) } echo(items) # Outputs: [10,0,1,20] # Or start with few items: items = collector/[100,200] { collect(10) for(i;2) collect(i) collect(20) } echo(items) # Outputs: [100,200,10,0,1,20]
- collector(h:Hash, body:Fun) Source: stdlib.ngs:2765
Defines collector { ... collect(...) ... } behaviour for hashes Parameters
h Initial hash body The body after collector keyword and initial value, wrapped in a function "collector/{'my': 'hash'} THIS_CODE" Returns
Constructed arrayExample
arr = [{"Name": "n1", "Value": "v1"},{"Name": "n2", "Value": "v2"}] my_hash = collector/{} arr.each(F(elt) collect(elt.Name, elt.Value)) echo(my_hash) # Outputs: {n1=v1, n2=v2}
- collector(n:Int, body:Fun) Source: stdlib.ngs:2776
Defines collector { ... collect(...) ... } behaviour for integers (summarizes collected items). Parameters
n Initial number body The body after collector keyword and initial value, wrapped in a function "collector/100 THIS_CODE" Returns
Constructed arrayExample
collector/0 { (1...10).each(collect) } # 55
- collector(s:Str, body:Fun) Source: stdlib.ngs:2786
EXPERIMENTAL! Do not use!
- collector(s:Stats, body:Fun) Source: stdlib.ngs:5203
Undocumented
- count(e:Eachable2, predicate:Fun) Source: stdlib.ngs:3900
Count number of key-value pairs in Hash that satisfy the predicate. Parameters
e Something to check, typically a Hash predicate Test function to be called with one key and one value at a time: predicate(k, v) Returns
IntExample
{'a': 1, 'b': 2, 'c': 11}.count(F(k, v) v>10) # 1
- deeper(mc:MatchContext, cb:Fun) Source: stdlib.ngs:1032
Undocumented
- deeper(mc:MatchContext, new_fields:Hash, cb:Fun) Source: stdlib.ngs:1039
Undocumented
- Diff(a:Arr, b:Arr, eq:Fun)experimental Source: stdlib.ngs:4519
EXPERIMENTAL! Do not use! Compare arrays using eq as equality test. 2*n*m comparisons Returns
ArrDiff
- dir(dirname:Str, cb:Fun, subtype:Any=false, raw:Any=false) Source: stdlib.ngs:5777
List directory contents and call cb with Path() of each found item. "." and ".." are excluded. Returns
unspecified at this time, do not count on itExample
's=Stats(); dir("tmp/v8", {s.push(A.Type().name)}, true); s # <Stats: {File=23, Dir=16}>'
- each(mm:MultiMethod, cb:Fun) Source: stdlib.ngs:421
Call cb for each method of the MultiMethod Example
echo.each(F(method) echo("${method.params().name.join(", ")}"))
- each(s:Success, fun:Fun) Source: stdlib.ngs:922
Run fun with wrapped value.
- each(f:Failure, fun:Fun) Source: stdlib.ngs:932
No-op, returns f Returns
f
- each(al:ArrLike, cb:Fun) Source: stdlib.ngs:1908
Call cb for each element in the underlying array. Returns
al
- each(hl:HashLike, cb:Fun) Source: stdlib.ngs:2061
Iterate over keys and values. Returns
hlExample
my_hashlike.each(F(k, v) echo("$k=$v"))
- each(s:Set, cb:Fun) Source: stdlib.ngs:2201
Call cb for each value in the set Returns
s
- each(r:NumRange, cb:Fun) Source: stdlib.ngs:2659
Iterates over the elements of r, passing each in turn to cb. Parameters
cb Function to be called with values from r Returns
rExample
s=0 (1...10).each(F(i) { global s; s+=i }) echo(s) # Outputs: 55
- each(arr:Arr, cb:Fun) Source: stdlib.ngs:3028
Iterates over the elements of arr, passing each in turn to cb along with args: cb(ITEM) Parameters
cb Function to be called with values from arr Returns
arrExample
s=0 [1,2,3].each(F(i) { global s; s+=i }) echo(s) # Outputs: 6
- each(arr:Arr, n:Int, cb:Fun) Source: stdlib.ngs:3077
Process each N elements of an Array at a time. Throws InvalidArgument if number of items in arr is not divisible by n. cb is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1 Parameters
arr Items to iterate in chunks of n n Number of items in chunk cb Function to be called with values from arr Returns
arrExample
[1,2,3,4].each(2, F(a, b) echo("$a - $b")) # Outputs: "1 - 2" and on the next line "3 - 4"
- each(h:Hash, cb:Fun) Source: stdlib.ngs:3694
Iterate a Hash. Parameters
h Hash to iterate cb Function to call with successive keys and values Returns
hExample
{"a": 1, "b": 2}.each(F(k, v) echo("$k=$v")) # Outputs: "a=1" and on the next line "b=2"
- each(fb:FullBox, cb:Fun) Source: stdlib.ngs:4240
Call cb with the value of the FullBox Returns
fbExample
Box(10).each(echo) # Output: 10
- each(eb:EmptyBox, cb:Fun) Source: stdlib.ngs:4245
Do nothing Returns
ebExample
Box(null).each(echo) # No output
- each(n:Int, cb:Fun) Source: stdlib.ngs:4649
Iterate from zero up to but not including n Parameters
cb Function to call with current number Returns
nExample
10.each(echo) # Outputs numbers from 0 to 9 inclusive, one on each line
- each(s:Str, cb:Fun) Source: stdlib.ngs:4759
Iterates over all string characters (currently bytes). Parameters
cb Function to be called with each character from s Returns
sExample
"abc".each(echo) # Output: # a # b # c
- each(d:Dir, cb:Fun) Source: stdlib.ngs:5809
Call cb for each entry in the directory with a subtype of Path as an argument Returns
d
- each(rd:ResDef, cb:Fun)
Call cb with properties of each found resource Returns
rdExample
AWS::Instance().each(F(i) echo(i.InstanceId))
- each(i:Iter, cb:Fun)
Calls cb with each element from i Returns
iExample
Iter(10).each(echo) # Prints 0 to 9
- each(t:Table, cb:Fun)
Please do not use. This method might change. Call cb with each table row.
- each(t:Table, cb:Fun)
Please do not use. This method might change. Call cb with each table row.
- each_chunk(e:Eachable1, n:Int, cb:Fun)experimental Source: stdlib.ngs:3608
Call cb with array of maximum length of n, repeatedly for all items of e. TODO: better doc, rename to each() to be consistent with each(Arr, Int, Fun)?
- each_group_test(tr:TestsResults, cb:Fun)
Undocumented
- each_idx_key_val(hl:HashLike, cb:Fun) Source: stdlib.ngs:2076
Undocumented
- each_idx_key_val(h:Hash, cb:Fun) Source: stdlib.ngs:3754
Iterate a Hash. Parameters
h Hash to iterate cb Function to call with successive indexes, keys and values Returns
hExample
{"a": 1, "b": 2}.each_idx_key_val(F(idx, k, v) echo("[$idx] $k=$v")) # Outputs: "[0] a=1" and on the next line "[1] b=2"
- each_idx_val(e:Eachable1, cb:Fun) Source: stdlib.ngs:3039
Iterates over elements of e, passing each in turn to cb along with index and args: cb(INDEX, ITEM) Returns
eExample
"abc".each_idx_val(F(idx, val) echo("Element #$idx equals to $val"))
- each_idx_val(arr:Arr, cb:Fun) Source: stdlib.ngs:3050
Iterates over the elements of arr, passing each in turn to cb along with index and args: cb(INDEX, ITEM) Returns
arrExample
[10,20,30].each_idx_val(F(idx, val) echo("Element #$idx equals to $val"))
- eachk(h:Hash, cb:Fun) Source: stdlib.ngs:3733
Iterate a Hash. Parameters
h Hash to iterate cb Function to call with successive keys Returns
h
- eachv(h:Hash, cb:Fun) Source: stdlib.ngs:3741
Iterate a Hash. Parameters
h Hash to iterate cb Function to call with successive values Returns
h
- filter(hl:HashLike, predicate:Fun) Source: stdlib.ngs:2088
Filter hash. Build new HashLike with kev-value pairs selected by predicate. Parameters
predicate Test function to be called with one key and one value at a time. Returns
value of the same type as hlExample
my_hashlike.filter(F(k, v) k == 'a')
- filter(h:Hash, predicate:Fun) Source: stdlib.ngs:3828
Filter a hash. Build new hash with kev-value pairs selected by the given predicate. Parameters
h Source hash predicate Test function to be called with one key and one value at a time: predicate(k, v) Example
{'a': 1, 'b': 2}.filter(F(k, v) k == 'a') # {'a': 1}
- filter(rd:ResDef, predicate:Fun)
Create new resource definition by filtering resources of rd. Parameters
rd Original resource definition. Not modified. Returns
ResDefExample
# Get instances with last private IP octet less than 20: AWS::Instance().filter({A.PrivateIpAddress.split(".")[-1].Int()<20})
- finally(b:Block, cleanup:Fun)experimental Source: stdlib.ngs:223
Add function to run before exiting the block. The functions added will be run in reverse order.
- finally(body:Fun, cleanup:Fun) Source: stdlib.ngs:2822
Run cleanup after successful execution of body or exception in body Parameters
body Main code to execute cleanup Cleanup code to execute Returns
Whatever body call returnsExample
finally( { while entry = c_readdir(d) { ... } }, { ... c_closedir(d) ...} ) # Alternative function call syntax: finally( body = { while entry = c_readdir(d) { cb(Path(dirname / entry.d_name, subtype=subtype)) } } cleanup = { r = c_closedir(d) r != 0 throws DirFail('Failed to close directory after listing').set('dirname', dirname) } )
- flat_map(e:Eachable1, mapper:Fun) Source: stdlib.ngs:1435
Map and flatten. Applies mapper to each element of e, collects results, and flattens the results (one level). Example
[2,0,4].flat_map(F(e) Result({ 12 / e}).Box()) # [6, 3] [2,0,4].flat_map(F(e) [1, e*2]) # [1,4, 1,0, 1,8]
- group(e:Eachable1, k:Fun, v:Fun=method) Source: stdlib.ngs:4106
Group items from e by key returned by k Returns
Hash with Arr valuesExample
["ab", "ac", "ba", "bc", "bd"].group(F(x) x[0]) # {a=[ab,ac], b=[ba,bc,bd]} [["a", 1], ["b", 2], ["a", 3]].group(X[0], X[1]) # {"a": [1,3], "b": [2]}
- Hash(e:Eachable1, cb:Fun) Source: stdlib.ngs:3994
Create a Hash from keys in Eachable1 using cb for values calculation Parameters
e Keys of the hash to build cb Function to be called with one key at a time. Should calculate a value for the given key. Returns
HashExample
Hash([1,2], F(x) x*2) # {1: 2, 2: 4}
- init(t:Transformed, transformation:Fun, pattern:Any) Source: stdlib.ngs:1208
Undocumented
- init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:5247
Creates and runs a thread. The code that the created thread runs is f, which is passed arg.
- init(t:Thread, f:Fun, arg:Any) Source: stdlib.ngs:5275
Creates and runs a thread. The code that the created thread runs is f, which is passed arg.
- init(t:Thread, f:Fun) Source: stdlib.ngs:5280
Creates and runs a thread. The code that the created thread runs is f without arguments.
- init(t:Thread, name:Str, f:Fun) Source: stdlib.ngs:5285
Creates and runs a thread. The code that the created thread runs is f without arguments.
- init(i:MapIter, upstream_iter:Iter, mapper:Fun)
EXPERIMENTAL! Do not use!
- init(i:FunIter, f:Fun)
Undocumented
- init(mp:MethodParams, f:Fun)
Undocumented
- init(md:MethodDescription, method:Fun)
Undocumented
- init(md:MethodDescription, containing_nd:NamespaceDescription, name:Str, mmd:MultiMethodDescription, method:Fun)
Undocumented
- init(md:MethodDescription, containing_nd:NamespaceDescription, name:Str, method:Fun)
Undocumented
- Iter(f:Fun)
Undocumented
- lines(s:Str, cb:Fun) Source: stdlib.ngs:4988
Split s to strings using end-of-line separators and call cb for each one of the lines. TODO: More efficient implementation, which would not have temporary array of all lines. Parameters
cb Function to be called with each line
- lines(f:File, cb:Fun) Source: stdlib.ngs:6239
Iterate over lines of the file Parameters
f Closed File cb function to call with successive lines from the file
- lines(p:Process, cb:Fun) Source: stdlib.ngs:7152
Iterate lines of Process' stdout, calling cb with successive lines. Warning: current implementation waits for the process to finish, accumulates all its stdout, and only then starts calling cb for each line.
- lines(pp:ProcessesPipeline, cb:Fun) Source: stdlib.ngs:7168
Wait for pp and return call cb for each line of stdout of last process. Warning: current implementation waits for the processes to finish, accumulates all stdout of the last process, and only then starts calling cb for each line. Returns
Arr of Str
- lines(f:MaybeFile, cb:Fun)
Like lines(File) but cb is never called if the file is not present
- map(s:Success, fun:Fun) Source: stdlib.ngs:928
Run fun with wrapped value. If exception is thrown, Failure is returned; otherwise Success with new value is returned. Returns
Result
- map(f:Failure, fun:Fun) Source: stdlib.ngs:936
No-op, returns f Returns
f
- map(e:Eachable, mapper:Fun) Source: stdlib.ngs:1427
Map e to an Arr (array) of values using mapper. Parameters
e Object of any type that has each(e, callback) implemented Returns
ArrExample
[1,2,3].map(X*4) # [4,8,12]
- map(arr:Arr, n:Int, mapper:Fun) Source: stdlib.ngs:3098
Map each N elements of an Array at a time. mapper is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1 Throws InvalidArgument if number of items in arr is not divisible by n. mapper is called as mapper(eltI, ..., eltJ) where I is multiple of n and J is I+n-1 Parameters
arr Items to iterate in chunks of n n Number of items in chunk mapper Function to be called with values from arr Returns
ArrExample
[1,2,3,4].map(2, F(a,b) "$a=$b").join("&") # Outputs: 1=2&3=4
- map(h:Hash, mapper:Fun) Source: stdlib.ngs:3766
Map a Hash Parameters
h Hash with source keys and values mapper Function to be called with keys and values from h Returns
ArrExample
{'a': 1, 'b': 2}.map(F(k, v) "${k}-$v") # ['a-1', 'b-2']
- map(fb:FullBox, mapper:Fun) Source: stdlib.ngs:4230
Map FullBox value Parameters
mapper mapper to be called with the FullBox value Returns
FullBox with value returned by mapperExample
Box(10).map(X*2) # <FullBox val=20>
- map(eb:EmptyBox, mapper:Fun) Source: stdlib.ngs:4235
Do nothing Returns
ebExample
EmptyBox().map(X*2) # <EmptyBox>
- map(i:Iter, mapper:Fun)
EXPERIMENTAL! Do not use!
- map_base_idx(base:Any, n:Int, mapper:Fun)deprecated Source: stdlib.ngs:1731
Deprecated. Map when there is more than one element. If there is exactly one element, it's left as is Parameters
mapper Will be called with zero based index and successive elements from arr Returns
Arr
- map_idx_key_val(hl:HashLike, mapper:Fun) Source: stdlib.ngs:2081
Undocumented
- map_idx_key_val(h:Hash, mapper:Fun) Source: stdlib.ngs:3776
Map a Hash Parameters
h Hash with source keys and values mapper Function to be called with sequential zero-based index, keys and values from h Returns
ArrExample
{'a': 1, 'b': 2}.map_idx_key_val(F(i, k, v) "${i}-${k}-$v") # ['0-a-1', '1-b-2']
- map_idx_val(e:Eachable1, mapper:Fun) Source: stdlib.ngs:3060
Map an Eachable1 to an Arr (array) of values using mapper mapper is called as mapper(INDEX, ITEM) Returns
New ArrExample
echo("Array items: " + ArrLike().push(10).push(20).push(30).map_idx_val(F(idx, val) "[$idx]=$val").join(", ")) # Outputs: Array items: [0]=10, [1]=20, [2]=30
- mapk(h:Hash, mapper:Fun) Source: stdlib.ngs:3785
Map Hash keys. Build new Hash with same values as in h but keys mapped by mapper. Parameters
h Source hash mapper Function to be called with keys Returns
HashExample
mapk({"a": 1}, F(k) k+"z") # {"az": 1}
- mapkv(h:Hash, mapper:Fun) Source: stdlib.ngs:3816
Map Hash keys and values. Build new Hash with keys and values mapped by mapper. Parameters
h Source hash mapper Function to be called with keys and values Example
mapkv({"a": 1}, {[A+"zz", B+10]}) # {"azz": 11}
- mapo(e:Eachable1, mapper:Fun)experimental Source: stdlib.ngs:1453
EXPERIMENTAL! Do not use! Map e to same type. Mnemonics: "map original" / "MAP to Original type". Parameters
e object of any type that has each(e, callback) implemented Eachable1. WARNING: instances of same type as e must have empty constructor and push() method. Returns
Of same type as eExample
Set([1,2]).mapo(X*2) # Set([2,4])
- mapo(s:Str, mapper:Fun) Source: stdlib.ngs:5029
Map a string, character by character. Returns
StrExample
"abcd".mapo(F(x) if x == "b" then "X" else x) # "aXcd" "abcd".mapo(X.when("b", "*")) # "a*cd"
- mapv(h:Hash, mapper:Fun) Source: stdlib.ngs:3804
Map Hash values. Build new Hash with same keys as in h but values mapped by mapper. Parameters
h Source hash mapper Function to be called with values Returns
HashExample
LEN = 3 lines_ = read("/usr/share/dict/words").lines() long_lines = lines_.filter({A.len()>LEN}) prefix_to_lines = long_lines.group(F(line) line[0..LEN]) # {"pfx1": ["pfx1a", "pfx1b", ...], "pfx2": ["pfx2a", "pfx2b", ...], ...} prefix_to_count = prefix_to_lines.mapv(len) # {"pfx1": 30, "pfx2": 35, ...} top = prefix_to_count.Arr().sort(F(a, b) b[1] <= a[1]).Hash() top .= limit(10) echo(top) # Outputs: {con=1219, dis=1001, pro=808, pre=607, com=600, int=543, tra=498, ove=431, per=422, imp=421}
- merge_sorted(a:Arr, b:Arr, lte:Fun) Source: stdlib.ngs:3537
Merge sorted arrays. Parameters
lte Less-then-or-equal function to use for comparison of items in a and b Returns
ArrExample
merge_sorted([1,3,10], [0, 7], (<=)) # [0, 1, 3, 7, 10]
- only(pattern:Any, mapper:Fun)deprecated Source: stdlib.ngs:1466
Deprecated. Use when(val, pat, new_val) instead. Transform mapper to handle only items matching pattern. Non-matching items will be returned as is. Example
["abc", 1, "def", 2].map(only(Int, X*2)) # ["abc", 2, "def", 4]
- only(val:Any, pattern:Any, mapper:Fun)deprecated Source: stdlib.ngs:1476
Same as val.when(pattern, mapper)
- opt_prop(rd:ResDef, name:Str, props:Hash, cb:Fun)
Run cb with optional resource property if it exists, uses opt_prop(ResDef, Str, Hash)
- partial(f:Fun, *bind_args:Arr)deprecated Source: stdlib.ngs:681
Returns partially-applied function Parameters
f The base function
- partial_tail(f:Fun, *bind_args:Arr)deprecated Source: stdlib.ngs:689
Same as partial() but the bound arguments are last ones
- pmap(e:Eachable1, mapper:Fun) Source: stdlib.ngs:5331
Parallel map. Runs mapper in threads. Each thread processes one element from the array but this might change in future (preserving the total number of calls to mapper and the order of results). Number of threads is limited to the lower of the two: processors * 100 or 1000. Returns
Arr, result of applying mapper to elements of e, preserving the order.Example
pages_texts = abs_pages_urls.pmap(F(url) `lynx -dump $url`)
- pmap(e:Eachable1, threads:Int, mapper:Fun) Source: stdlib.ngs:5352
Parallel map. Runs mapper in "threads" total threads. Parameters
e Eachable1 to be mapped threads number of threads to use mapper called with elements from e Returns
Arr, result of applying mapper to elements of e, preserving the order.Example
pages_texts = abs_pages_urls.pmap(F(url) `lynx -dump $url`)
- ptimes(n:Int, cb:Fun) Source: stdlib.ngs:5377
Run cb in n parallel threads. Each thread runs one cb but this might change in future (preserving the total n calls to cb).
- reduce(something:Eachable1, start:Any, f:Fun) Source: stdlib.ngs:1689
Combine items to a single value using the supplied binary function First f is applied to start and the first element of something then on each step f is applied to previous result and next element of something. Parameters
something object of any type that has each(something, callback) implemented start First argument of f, for the first call of f f The combining function Example
F sum(something) something.reduce(0, (+))
- reduce(e:Eachable1, f:Fun) Source: stdlib.ngs:1707
Combine items to a single value using the supplied binary function First f is applied to the first two elements of e then on each step f is applied to previous result and next element of e. Throws EmptyEachableFail if e has no elements. If e has only one element, that element is returned. Parameters
e object of any type that has each(e, callback) implemented f The combining function Example
F sum(e) e.reduce((+))
- reject(h:Hash, predicate:Fun) Source: stdlib.ngs:3838
h.filter(not + predicate)
- replace(s:Str, r:RegExp, mapper:Fun) Source: stdlib.ngs:7813
Replace all occurrences of r Parameters
mapper Function that will be called with one matching string at a time that provides the replacement Returns
StrExample
"x10ab20c30y".replace(/[0-9]+/, F(match_text) "[$match_text]") # "x[10]ab[20]c[30]y"
- Result(fun:Fun) Source: stdlib.ngs:878
Runs the computation and wraps the result: a value is wrapped in Success and an exception is wrapped in Failure. Returns
Success or Failure
- retry(times:Int=60, sleep:Any=1, logger:Fun=method, success_predicate:Any=method, title:Any='<retry>', progress_cb:Fun=method, success_cb:Fun=method, fail_cb:Any=method, body:Fun=method) Source: stdlib.ngs:8379
Retry. Executes given "body" "times" times. Throws RetryFail if all calls fail and fail_cb is not provided. Parameters
times Limit of times to run "body" sleep Either sleep in seconds between tries or Iter that returns successive sleep times in seconds logger Function to use to log attempts, caught body exceptions and sleep times. Defaults to stdlib's debug. success_predicate CANDIDATE FOR REMOVAL. Run against body results to. Says whether the attempt succeeded. Defaults to Bool. title Prefix strings sent to logger with this string. Defaults to "<retry>". progress_cb Called before each attempt with (1) current attempt number and (2) limit of attempts ("times"). Defaults to do nothing. success_cb Called when body succeeds with the result that comes from body. Defaults to identity function. fail_cb If passed, called if all attempts fail. Defaults to null. Returns
Any. Result of success_cb or result of fail_cb.Example
page = retry(times=10, sleep=ExpBackIter(), body={ try `curl "http://flaky-site.com"` })
- sort(a:Arr, lte:Fun=method) Source: stdlib.ngs:3566
Sort an array. Parameters
lte Less-then-or-equal function to use for comparison of the items in a Returns
ArrExample
sort([0,5,3,-1], (<=)) # [-1, 0, 3, 5]
- sort(a:Arr, field:Str, lte:Fun=method) Source: stdlib.ngs:3579
Sort an array based on field value Parameters
lte Less-then-or-equal function to use for comparison of the items' fields Returns
ArrExample
[{'x': 1}, {'x': 5}, {'x': 3}].sort('x') # [{'x': 1}, {'x': 3}, {'x': 5}]
- sort(h:Hash, lte:Fun=method) Source: stdlib.ngs:4153
Sort a Hash. Parameters
lte Less-then-or-equal function to use for comparison of the keys in h Returns
HashExample
{"b": 2, "c": 3, "a": 1}.sort() # {"a": 1, "b": 2, "c": 3}
- sortk(h:Hash, lte:Fun=method) Source: stdlib.ngs:3912
Sort Hash by keys Returns
HashExample
{'b': 2, 'c': 11, 'a': 1}.sortk() # {'a': 1, 'b': 2, 'c': 11}
- sortv(h:Hash, lte:Fun=method)experimental Source: stdlib.ngs:3918
Undocumented
- tap(val:Any, cb:Fun) Source: stdlib.ngs:1740
Call cb with val Returns
valExample
long_computation_part1().tap(F(x) echo("DEBUG: $x")).long_computation_part2()
- test(name:Str, f:Fun)
Runs f as a test. Parameters
name Human readable name of the test. f A Fun that will either throw TestFail, return TestMessage. Other values are ignored by the testing framework.
- test(results:TestsResults, group:Str, name:Str, f:Fun, critical:Bool=true)
EXPERIMENTAL! Do not use! Runs f as a test in a test group
- the_one(e:Eachable1, pattern:Any=method, body:Fun=method, found_more:Any=block, found_none:Any=block) Source: stdlib.ngs:1601
Find the only element that matches the pattern and execute given code with the value Parameters
body The code to execute when exactly one element that matches the pattern was found. Executed with the found value. It's value will be returned as result of the_one(). found_more The code to execute when more than one element matches the pattern. It's value will be returned as result of the_one(). Defaults to throwing an exception. found_none The code to execute when none of the elements match the pattern. It's value will be returned as result of the_one(). Defaults to exception. Returns
Result of running on of the following: body, found_more, found_noneExample
F name(dn:MethodDocNode) { dn.children.the_one(MethodNameDocNode).text[0] }
- time(cb:Fun) Source: stdlib.ngs:8261
Mesure running time of cb in microseconds Returns
Int
- times(n:Int, cb:Fun) Source: stdlib.ngs:4660
Call cb n times without arguments. Parameters
cb Function to call Example
r=0; 5.times(F() r=r+2); # r is now 10
- uniq(e:Eachable1, cb:Fun=method) Source: stdlib.ngs:3162
Return unique values. Warning: uses Hash so comparison is not using == but a built-in hash keys comparison. Returns
Of same type as eExample
[1,2,2,3,4,4].uniq() # [1,2,3,4] [{"a": 1, "z": 10}, {"a": 1, "z": 20}, {"a": 2, "z": 30}].uniq(X.a) # [{"a": 1, "z": 10}, {"a": 2, "z": 30}]
- Value(x:Fun, *args:Arr) Source: stdlib.ngs:731
Used for converting default values or functions to values Returns
x(*args)
- AWS::regions(cb:Fun)
Call cb in parallel threads, each with AWS region name as argument. Parameters
cb Must return an array. regions() sets .Region in the result and flattens the results Returns
ArrExample
ins = AWS::regions({ ``aws ec2 describe-instances --region $A $*filters`` })
- AWS2::regions(cb:Fun, regs:Arr=[])
Call cb in parallel threads, each with AWS region name as argument. Parameters
cb Must return an array. regions() sets ._Region in the result and flattens the results Returns
ArrExample
ins = AWS2::regions({ ``aws ec2 describe-instances --region $A $*filters`` })
- Doc::each_child(p:Doc::Part, cb:Fun)
Undocumented
- Doc::map_children(p:Doc::Part, mapper:Fun)
Undocumented
- Doc::Transformer(x:Fun)
Undocumented
- Doc::visit(p:Doc::Part, cb:Fun, parents:Arr=[])
Undocumented