Module scutil

ScUtil is StoneCypher's Utility Library, a collection of hundreds of routines of a variety of topics which have aggregated from reuse in other projects.

Copyright © 2007 - current John Haugeland, All Rights Reserved

Version: $Revision: 137 $

Introduced in: September 14, 2007

Authors: John Haugeland (stonecypher@gmail.com).

References

Description

ScUtil is StoneCypher's Utility Library, a collection of hundreds of routines of a variety of topics which have aggregated from reuse in other projects.

This file has aggregated dozens of useful miscellaneous routines which I'm releasing to the public in good faith. There's no particular direction to this library; any time I write a routine that I tend to use in a lot of situations, which isn't already meaningfully classifiable into one of my other libraries, I throw it in here. This has ended up creating a range of unrelated functionality on which most of my other libraries depend heavily. Have fun digging around.

Routines by Category

The most common way for people to find what they need.

Conversion

Routines for converting between basic types, annotated types and user types
hex_to_int/1, byte_to_hex/1, nybble_to_hex/1, io_list_to_hex/1, list_to_number/1, int_to_u32_iolist/1, u32_iolist_to_int/1, u32_iolist_to_int/4, int_to_u64_iolist/1, u64_iolist_to_int/1, u64_iolist_to_int/8

Counters

Routines for tracking counters shared between processes
counter/1, reset_counter/1, inc_counter/1, inc_counter/2, dec_counter/1, dec_counter/2, adjust_counter/2, set_counter/2

Dispatch

Routines for managing send/receive patterns between processes and process sets
call_after/2, call_after/3, call_after/4

Documentary

Routines whose purpose is to clarify dependant code by presenting their name, rather than routine behavior, as well as to establish standard result messages where appropriate
even_or_odd/1, absolute_difference/2, receive_one/0, start_register_if_not_running/3, start_register_if_not_running/4, start_register_if_not_running/5 (see also square/1)

List

Routines for operating on lists of data augmenting the standard lists module.
permute/1, combinations/2, shuffle/1, sanitize_tokens/2, shared_keys/1, shared_keys/2, shared_keys/3, all_unique_pairings/1, walk_unique_pairings/2, zip_n/1, count_of/2 (see also random_from/3, random_from_weighted/1)

Math

Routines for higher math computation missing from the standard math module.
list_product/1, dot_product/2, cross_product/2, vector_magnitude/1, normalize_vector/1, root_mean_square/1, root_sum_square/1, tuple_sum/1, square/1, mod/2

Network

Routines for network behaviors and management.
standard_listener/3

Parallelism

Routines for manipulating behavior across sets of parallel processes.
map_reduce/2, map_reduce/3, map_reduce/4

Persistence

Routines to simplify and automate the storage of local information.
make_notebook/1, remove_notebook/1, has_notebook/1, annote/3, read_note/2, has_note/2, remove_note/2

Probability

Routines to calculate the likelihoods of things.
bayes_likelihood_of/3 (see also count_of/2, histograph/1)

Random

Routines to provide complex pseudorandom services and convenience wrappers to augment the standard random module.
grid_scatter/2, srand/0, srand/3, rand/1, random_from/1, random_from/2, random_from/3, random_from_weighted/1 (see also shuffle/1)

Regex

Routines to provide a convenience wrapper for the standard regex module.
regex_read_matches/2, regex_read_matches/3

Serialism

Routines for manipulating behavior in repeat series within a single process.
multi_do/3, multi_do/4

Statistics

Means
Routines for finding various kinds of mean values for numeric lists
arithmetic_mean/1, geometric_mean/1, harmonic_mean/1, weighted_arithmetic_mean/1, arithmetic_mean/1, centroid/1
Descriptive
Routines which provide informative measurements of numeric lists
median/1, mode/1, histograph/1, std_deviation/1, median_absolute_deviation/1, moment/2, moments/1, moments/2, central_moment/2, central_moments/1, central_moments/2, skewness/1, kurtosis/1 (see also count_of/2, root_mean_square/1)
Normals
Routines to calculate the various normals of vectors
amean_vector_normal/1, gmean_vector_normal/1, hmean_vector_normal/1
Ranking
Routines to provide statistical rankings of lists
ranks_of/1, tied_ranks_of/1, ordered_ranks_of/1
Correlations
Routines to measure the statistical correlations between two numeric lists
kendall_correlation/1, kendall_correlation/2, pearson_correlation/1, pearson_correlation/2, spearman_correlation/1, spearman_correlation/2

String

Routines to augment the existing string module. All scutil string routines are safe for widechar lists.
sanitize_filename/1, to_lines/1

Utility

Routines which don't classify well into larger categories
type_of/1, get_module_attribute/1, get_module_attribute/2, scan_svn_revision/1

License

ScUtil is MIT license, because the author feels very strongly against the GPL.

Registration

ScUtil is free and may be used at discretion. However, the author would appreciate three things if you have time:

  1. Putting a link to the main domain http://scutil.com/ on your site(s) to help get the word out
  2. Marking yourself a user of the library on ohloh (press the button to the left if you're already a user), to help get the word out
  3. Dropping me an email at stonecypher@gmail.com, to let me know where my library has ended up. It's interesting.

Thanks

ScUtil has profited significantly from the donations of time, understanding and code given by a variety of generous friends and strangers. The list of small tweaks would be prohibitive, but significant influence on this library is due the following people, in alphabetical order (the least fair of all generic orderings):

Data Types

byte()

byte() = integer()

A byte must be an integer in the range 0-255, inclusive. (Technically this is an octet, not a byte, but the word byte is extensively misused throughout the erlang documentation and standard library, which makes this an important concession, so we're when-in-Rome-ing.)

coord()

coord() = tuple()

Every member of a coord() is a number(). Represents a coordinate, which may imply a sized cartesian space. Many functions expect integer coordinates; the type does not require them. This type does not define member count. If your function requires a specific count of members, name it, as in a coord2() or coord3().

coord2()

coord2() = {number(), number()}

Represents a coordinate, which may imply a sized rectangle. Many functions expect integer coordinates; the type does not require them.

coord2list()

coord2list() = list()

All members of a coord2list() must be coord2()s.

coord3()

coord3() = {number(), number(), number()}

Represents a coordinate, which may imply a sized 3d box region. Many functions expect integer coordinates; the type does not require them.

coord3list()

coord3list() = list()

All members of a coord3list() must be coord3()s.

coordlist()

coordlist() = list()

All members of a coordlist() must be coord()s. All member coordinates must be of the same size, though this type does not define what that size is. If your function requires a specific count of members, name it, as in a coord2list() or coord3list().

filterfunction()

filterfunction() = function()

Filter functions are 1ary binary predicates - they accept an argument and return either true or false.

gridsize()

gridsize() = coord2() | integer()

Coordinates are the width and height of a (1,1) originated grid; as such, coordinates are of the range [1,X] , [1,Y] inclusive, and returned in the form {A,B}. The integer form implies a square grid.

handler()

handler() = {handler, PID} | {handler, PID, IdHandle} | no_handler_pid

Use a handler() to provide handling behavior to functions like call_after/1. The PID given is the pid to which result messages will be sent. If an IdHandle is given, that IdHandle is passed back with the result, to pass extra information back to identify which result it is. The atom no_handler_pid specifies that you would prefer the result to be discarded.

hexchar()

hexchar() = integer()

Integer must be in the range $0 - $9, the range $a - $f, or the range $A - $F, all inclusive, for inputs; outputs will always use lower case.

hexstring()

hexstring() = list()

All elements of the list must be of type hexchar().

io_list()

io_list() = list()

Every list member of an io_list() must be a byte().

keylist()

keylist() = keylist()

All members of keylists are tuples of two-or-greater arity, and the first element is considered their key in the list. List keys are unique; therefore [{a,1},{b,1}] is a keylist, but [{a,1},{a,1}] is not.

list_of_lists()

list_of_lists() = list()

Every member of a list_of_lists() is a list().

non_negative_integer()

non_negative_integer() = integer()

A non_negative_integer() must be equal to or greater than zero.

numeric_tuple()

numeric_tuple() = tuple()

Every member of a numeric_tuple() must be a number().

numericlist()

numericlist() = list()

All members of a numeric list must be number()s.

nybble()

nybble() = integer()

A nybble must be an integer in the range 0-15, inclusive.

positive_integer()

positive_integer() = integer()

Positive integer must be greater than zero.

ranking()

ranking() = {Ranking::number(), Value::any()}

Values are usually number()s, but do not have to be with custom ranking predicates.

rankinglist()

rankinglist() = list()

Members of a rankinglist() must be ranking()s.

relaxed_numeric_tuple()

relaxed_numeric_tuple() = numeric_tuple()

Relaxed numeric tuples are allowed to contain non-numeric elements, which are treated as zero for purposes of computation.

sanitizer()

sanitizer() = list() | filterfunction()

Sanitizers are used by sanitize_tokens/2 for input sanitization; they define what parts of an input list are valid, and the remainder are removed. Sanitizers may either be a list of acceptable elements or a filter function.

seven_vector()

seven_vector() = vector()

A seven-vector always has seven elements, so this can be expressed as the alternation {A::number(), B::number(), C::number(), D::number(), E::number(), F::number(), G::number()} | [A::number(), B::number(), C::number(), D::number(), E::number(), F::number(), G::number()].

sorted_keylist()

sorted_keylist() = keylist()

A sorted keylist is a keylist in the order provided by lists:sort/1. Because of erlang tuple ordering rules and the fact that keylist keys are unique, this means the list will be ordered by key.

stringlist()

stringlist() = list()

Every member of a stringlist() is a string().

three_or_seven_vector()

three_or_seven_vector() = three_vector() | seven_vector()

three_vector()

three_vector() = vector()

A three-vector always has three elements, so this can be expressed as the alternation {A::number(), B::number(), C::number()} | [A::number(), B::number(), C::number()].

timestamp()

timestamp() = {Megaseconds::non_negative_integer(), Seconds::non_negative_integer(), MicroSeconds::non_negative_integer()}

typelabel()

typelabel() = [integer | float | list | tuple | binary | bitstring | boolean | function | pid | port | reference | atom | unknown]

Used by type_of(), this is just any single item from the list of erlang's primitive types, or the atom unknown.

unit_vector()

unit_vector() = vector()

The hypoteneuse of a unit vector is precisely one unit long. Unit vectors are also called normalized or magnitude-normalized vectors.

vector()

vector() = list() | tuple()

Every member element of a vector() is a number().

vectorlist()

vectorlist() = list()

Every member element of a vectorlist() is a vector().

weightedvalue()

weightedvalue() = {Value::any(), Weight::number()}

Used by functions like weighted_arithmetic_mean/1 and random_from_weighted/1, weightedvalue()s represent a value with an associated importance or "weight".

weightlist()

weightlist() = list()

All members of weightlists must be weightedvalue()s.

Function Index

absolute_difference/2Documentary Takes the absolute value of the difference between the two arguments.
adjust_counter/2Counters Adds to a counter's value; if the counter was not already defined, it will become the value in the By argument.
all_unique_pairings/1(Deprecated.) List Generate every unique pair of elements from a list; deprecated in favor of combinations/2.
amean_vector_normal/1Statistics Returns the arithmetic mean of the elements of the unit vector for the vector provided.
annote/2Persistence Stores a key/value pair to a notebook file, overwriting a match existing key if present; if the notebook does not exist, it is automatically created.
annote/3Equivalent to annote(Notebook, [{NoteName, NewValue}]).
arithmetic_mean/1Statistics Take the arithmetic mean (often called the average) of a list of numbers.
bayes_likelihood_of/3Probability TODO Calculates the probability of a hypothetical event in the context of a dataset and a baseline given item, using Bayesian inference.
benchmark/2
benchmark/3
byte_to_hex/1Conversion Convert a byte() into a hexstring().
call_after/2Equivalent to call_after(Length, Func, [], {handler, self()}).
call_after/3Equivalent to call_after(Length, Func, Args, {handler, self()}).
call_after/4Utility Spawns a side process to non-blockingly make a call after a specified delay.
central_moment/2Statistics Takes the Nth cetral moment of a list.
central_moments/1Equivalent to [central_moment(List, N) || N <- [2, 3, 4]].
central_moments/2Equivalent to [central_moment(List, N) || N <- Moments].
centroid/1Statistics Calculates the coordinate which represents the per-axis arithmetic mean of a set of points.
combinations/2List Provides a list of every unique combination of input terms, order-ignorant; contrast permute/2.
count_bits/1Utility Counts the number of bits turned on in a sufficiently sized unsigned two's compliment integer representation of Num.
count_of/2Counts the number of instances of Item in List.
counter/1Counters Checks a counter's value; if the counter was not already defined, it will report zero.
cross_product/2Math Incomplete Calculates the cross product of two vectors (Incomplete represented as three_vector()s - no support yet for seven).
dec_counter/1Equivalent to adjust_counter(Name, -1).
dec_counter/2Equivalent to adjust_counter(Name, -1 * By).
diff_timestamp/2Utility Returns the difference, in seconds as a float, between two erlang timestamps as returned by erlang:now().
dot_product/2Math Incomplete Calculates the dot product of two vectors (Incomplete represented as numeric lists; tuples not yet supported).
elements/2
elements/3
elements/4
euclidean_distance/2Math Returns the distance between two coordinates in any N-space.
even_or_odd/1Documentary Documentary convenience function that returns the atoms even or odd for any integer.
every_flag_representation/1Lists Returns every interpretation of the list as a set of boolean flags, including all-off and all-on.
every_member_representation/1Equivalent to every_member_representation(Memberships, no_absence).
every_member_representation/2
expand_label/1
expand_labels/1
f32_iolist_to_int/1Equivalent to f32_iolist_to_int(A, B, C, D, little).
f32_iolist_to_int/2Equivalent to f32_iolist_to_int(A, B, C, D, Endianness).
f32_iolist_to_int/4Equivalent to f32_iolist_to_int(A, B, C, D, little).
f32_iolist_to_int/5
flesch_kincaid_readability/4
flesch_kincaid_readability_score/3
float_to_f32_iolist/1
float_to_f32_iolist/2
geometric_mean/1Statistics Take the geometric mean of a list of numbers.
get_module_attribute/1Utility Look up all attributes of a given module.
get_module_attribute/2Utility Buggy Look up an Erlang module attribute value by title.
get_module_feature/2
gmean_vector_normal/1Statistics Returns the geometric mean of the elements of the unit vector for the vector provided.
grid_scatter/2Random Return a Count-length list of non-repeating coordinates in a grid of specified size; useful for feature generation.
harmonic_mean/1Statistics Take the harmonic mean of a list of numbers.
has_bit/2Utility Checks whether a given bit is on in a sufficiently sized unsigned two's compliment integer representation of Num.
has_note/2Persistence Checks if a given note exists in a given notebook, returning boolean atoms as an answer.
has_notebook/1Persistence Returns a boolean true or false whether a notebook under a given filename already exists.
hex_to_int/1Conversion Convert a hexstring() or hexchar() into its numeric value.
histograph/1Statistics Takes a histograph count of the items in the list.
hmean_vector_normal/1Statistics Returns the harmonic mean of the elements of the unit vector for the vector provided.
implode/2
inc_counter/1Equivalent to adjust_counter(Name, 1).
inc_counter/2Equivalent to adjust_counter(Name, By).
int_to_u32_iolist/1Equivalent to int_to_u32_iolist(X, little).
int_to_u32_iolist/2
int_to_u64_iolist/1Equivalent to int_to_u64_iolist(X, little).
int_to_u64_iolist/2
interpret_flesch_kincaid_readability_score/1
io_list_to_hex/1Conversion Convert an io_list() to a hexstring().
isolate_signal/1
kendall_correlation/1Statistics Compute the Kendall Tau Rank Correlation Coefficient of a list of coordinate tuples.
kendall_correlation/2Equivalent to kendall_correlation(lists:zip(List1, List2)).
kurtosis/1Equivalent to central_moment(List, 4).
list_intersection/2Equivalent to list_intersection(List1, List2, unsorted).
list_intersection/3Efficiently computes the intersection of two lists.
list_product/1Math Takes the product of all numbers in the list.
list_to_number/1Conversion Converts a list into a number; integers will be returned if there is no mantissa in the list representation.
make_notebook/1Persistence (Called automatically) Creates a "notebook", which is just a convenience wrapped DETS set table.
map_reduce/2Equivalent to map_reduce(Function, Workload, 1, nodes()).
map_reduce/3Equivalent to map_reduce(Function, Workload, JobsPerNode, nodes()).
map_reduce/4Parallelism Takes a workload, a function, a count of jobs per node and a node list, and distributes work on demand to available nodes until fulfilled.
median/1Statistics Takes the median (central) value of a list.
median_absolute_deviation/1Statistics Calculate the median absolute deviation of a numericlist().
minmax/1
mod/2Math Takes the modulus of an integer by another integer.
mode/1Statistics Takes the mode (most common) value(s) of a list, as a list.
module_abstract_code/1
module_atoms/1
module_has_function/2
moment/2Statistics Takes the Nth moment of a list.
moments/1Equivalent to [moment(List, N) || N <- [2, 3, 4]].
moments/2Equivalent to [moment(List, N) || N <- Moments].
multi_do/3Equivalent to multi_do(C, M, F, []).
multi_do/4Serialism Take an iteration count, a module name, a function name and an argument list, and repeatedly apply the argument list to the module/function, count times.
normalize_vector/1Math Returns the magnitude of a vector.
nybble_to_hex/1Conversion Convert a nybble() to a hexchar().
ordered_ranks_of/1Statistics Returns a tied ranked ordering of the list, ordered according to the input ordering rather than the sorted ordering.
pearson_correlation/1Statistics Compute the Pearson Correlation Coefficient of a list of coordinate tuples.
pearson_correlation/2Equivalent to pearson_correlation(lists:zip(List1, List2)).
permute/1Equivalent to permute(List, length(List)).
permute/2Utility Calculate either the full or the depth-limited permutations of a list, order sensitive; contrast combinations/2.
qsp_average/2Math Takes the quadratic scalar product average of a vector W and a list of vectors X.
rand/1Random Returns a pseudorandom integer on the range [0 - (Range-1)] inclusive.
random_from/1Equivalent to random_from(1, List, no_remainder).
random_from/2Equivalent to random_from(N, List, no_remainder).
random_from/3Random Take N non-repeating random elements from a list in undefined order.
random_from_weighted/1Random Take a random single item from a list with weighted probabilities.
ranks_of/1Statistics Returns a ranked ordering of the list without tie rankings.
read_note/2Persistence Read a key/value pair from a notebook file.
receive_one/0Utility Pop the front of the message queue and return it as {item,X}, or return nothing_there for empty queues; do not block.
record_member/2TODO: Needs Example Checks whether E is a member element of record R, analogous to lists::member(E, L).
regex_read_matches/2Equivalent to regex_read_matches(String, Reg, {0, 0}).
regex_read_matches/3Regex Take a string and a regular expression (and optionally an offset and length to trim to in each result), and return a list of all matches.
regex_read_matches/4Equivalent to regex_read_matches(String, Reg, {TrimFront, TrimLength}).
remove_note/2Persistence Removes a note by name from a given notebook.
remove_notebook/1Persistence Attempts to remove a notebook; all data in the removed notebook is lost permanently.
reset_counter/1Equivalent to set_counter(Name, 0).
root_mean_square/1Statistics Calculates the root mean square of the values in the list.
root_sum_square/1Math Calculate the magnitude (also known as the root sum square).
sanitize_filename/1String Sanitize an arbitrary string to be appropriate for Windows and Unix filesystems, and URLs.
sanitize_tokens/2List Remove unacceptable elements from an input list, as defined by another list or a filter function.
scan_svn_revision/1Utility Scans a module for an attribute svn_revision, parses it in the format expected from the svn:keyword Revision, and returns the version number as an integer.
set_counter/2Counters Sets a counter's value to a specific value.
shared_keys/1
shared_keys/2Equivalent to shared_keys/1, but skips sorting the lists (and thus requires pre-sorted lists), which may save significant work repetition.
shared_keys/3Equivalent to shared_keys/2, but skips sorting the lists (and thus requires pre-sorted lists), which may save significant work repetition.
shuffle/1Random Return a list with the original list's shallow members in a random order.
skewness/1Equivalent to central_moment(List, 3).
spearman_correlation/1Statistics Compute the Spearman's Rank Correlation Coefficient of a list of coordinate tuples.
spearman_correlation/2Equivalent to spearman_correlation(lists:zip(List1, List2)).
square/1Math Squares the input; convenient in list comprehensions to prevent recalculation, and clear in the fashion of documentary functions.
srand/0Random (Called automatically) Instantiates the random source, destroying a prior source if needed, and seeds the source with the clock, returning the seed used.
srand/3Random (Called automatically) Instantiates the random source, destroying a prior source if needed, and seeds the source with the three integer seed you provide, returning the seed used.
standard_listener/3Network Listens on a socket and manages the fast packet loss problem.
start_register_if_not_running/3Equivalent to start_register_if_not_running(node(), Name, Module, Function, []).
start_register_if_not_running/4Equivalent to start_register_if_not_running(node(), Name, Module, Function, Args).
start_register_if_not_running/5Documentary Check whether a process is registered locally, and if not, spawn it with a give function and arguments.
std_deviation/1Statistics Measures the standard deviation of the values in the list.
tied_ranks_of/1Statistics Returns a ranked ordering of the list with tie rankings.
to_lines/1String Cuts a string according to any of the three newline conventions (even mixed), and discards empty strings.
tuple_member/2Checks whether E is a member element of tuple T, analogous to lists::member(E, L).
tuple_sum/1Math Returns the sum of the numeric elements of a tuple, treating non-numeric elements as zero.
type_of/1Utility Fetch the type of the argument.
u32_iolist_to_int/1Equivalent to u32_iolist_to_int(A, B, C, D, little).
u32_iolist_to_int/2Equivalent to u32_iolist_to_int(A, B, C, D, Endianness).
u32_iolist_to_int/4Equivalent to u32_iolist_to_int(A, B, C, D, little).
u32_iolist_to_int/5
u64_iolist_to_int/1Equivalent to u64_iolist_to_int(A, B, C, D, E, F, G, H, little).
u64_iolist_to_int/2Equivalent to u64_iolist_to_int(A, B, C, D, E, F, G, H, Endianness).
u64_iolist_to_int/8Equivalent to u64_iolist_to_int(A, B, C, D, E, F, G, H, little).
u64_iolist_to_int/9
unit_scale_signal/1
vector_magnitude/1Math Returns the magnitude of a vector.
wait_until_terminate/0Equivalent to wait_until_terminate(quiet).
wait_until_terminate/1
walk_unique_pairings/2
weighted_arithmetic_mean/1Statistics Take the weighted arithmetic mean of the input values.
zip_n/1Equivalent to zip_n(Ls, to_tuple).
zip_n/2List Computes a zip on any sized group of lists, rather than just two or three as offered by the lists module.

Function Details

absolute_difference/2

absolute_difference(A::number(), B::number()) -> number()

Documentary Takes the absolute value of the difference between the two arguments. Offered mostly to make dependant code clearer.

  1> scutil:absolute_difference(1.25, 1).
  0.25

Introduced in: Version 39

adjust_counter/2

adjust_counter(Name::any(), By::number()) -> number()

Counters Adds to a counter's value; if the counter was not already defined, it will become the value in the By argument.

  1> scutil:counter(hello).
  0
 
  2> scutil:inc_counter(hello).
  1
 
  3> scutil:adjust_counter(hello, 3).
  4

Introduced in: Version 54

all_unique_pairings/1

all_unique_pairings(List::list()) -> tuple_list()

This function is deprecated: Use combinations/2 instead.

List Generate every unique pair of elements from a list; deprecated in favor of combinations/2.

  1> scutil:all_unique_pairings([a,b,c]).
  [{b,c},{a,b},{a,c}]

Introduced in: Version 31

amean_vector_normal/1

amean_vector_normal(VX::numeric_list()) -> number()

Statistics Returns the arithmetic mean of the elements of the unit vector for the vector provided.

Introduced in: Version 85

annote/2

annote(Notebook::filename(), List::kv_list()) -> ok | {error, E}

Persistence Stores a key/value pair to a notebook file, overwriting a match existing key if present; if the notebook does not exist, it is automatically created. DETS opening and closing are automatically managed.

Introduced in: Version 83

annote/3

annote(Notebook, NoteName, NewValue) -> any()

Equivalent to annote(Notebook, [{NoteName, NewValue}]).

arithmetic_mean/1

arithmetic_mean(InputList::numericlist()) -> float()

Statistics Take the arithmetic mean (often called the average) of a list of numbers.

  1> scutil:arithmetic_mean([1,2,3,4,5]).
  3.0

Introduced in: Version 33

See also: amean_vector_normal/1, geometric_mean/1, harmonic_mean/1, weighted_arithmetic_mean/1.

bayes_likelihood_of/3

bayes_likelihood_of(Event, Given, Data) -> float

Probability TODO Calculates the probability of a hypothetical event in the context of a dataset and a baseline given item, using Bayesian inference. Bayesian inference sorts through the dataset looking for baselines, counting them; when a given is found, the hypothetical event is also looked for, counting them only when the baseline given is located first. Then, the dividend of the hypothetical and given counts is returned as a likelihood estimation on the range [0.0 .. 1.0].

  1> scutil:bayes_likelihood_of(cancer, positive, [[cancer,positive],[healthy,negative],[cancer,positive],[healthy,positive]]).
  0.6666666666666666
 
  2> TestData = lists:duplicate(40,[healthy,nonsmoker]) ++ lists:duplicate(10,[healthy,smoker]) ++ lists:duplicate(7,[cancer,nonsmoker]) ++ lists:duplicate(3,[cancer,smoker]).
  [[healthy,nonsmoker], [healthy,nonsmoker], [healthy|...], [...]|...]
 
  3> scutil:bayes_likelihood_of(cancer, smoker, TestData).
  0.23076923076923078
 
  4> scutil:bayes_likelihood_of(cancer, nonsmoker, TestData).
  0.14893617021276595
This code and example data was derived from this tutorial. Todo: it seems like this could be rewritten to generate a set of likelihoods in an iteration, rather than a single likelihood then re-iterate

Introduced in: Version 110

benchmark/2

benchmark(Fun, Args) -> any()

benchmark/3

benchmark(Module, Func, Args) -> any()

byte_to_hex/1

byte_to_hex(TheByte::byte()) -> hexstring()

Conversion Convert a byte() into a hexstring(). The hexstring() result will always be two characters (left padded with zero if necessary).

  1> scutil:byte_to_hex(7).
  "07"
 
  2> scutil:byte_to_hex(255).
  "ff"

Introduced in: Version 20

call_after/2

call_after(Length, Func) -> any()

Equivalent to call_after(Length, Func, [], {handler, self()}).

call_after/3

call_after(Length, Func, Args) -> any()

Equivalent to call_after(Length, Func, Args, {handler, self()}).

call_after/4

call_after(Length::integer(), Func::function(), Args::atom(), Handler::handler()) -> {ok, spawned_worker, Worker::pid()}

Utility Spawns a side process to non-blockingly make a call after a specified delay. Will send the result as a message { call_after_result, Result } to the handler process, which is the calling process unless otherwise specified (with {handler,OtherPid} or the atom no_handler_pid). Delayed return value can include an ID, in the format { call_after_result, Result, IdHandle }, if the Handler PID is specified {handler,PID,ID}, to help distinguish between returned calls if needed.

  1> Dbl = fun(X) -> X*2 end.
  #Fun<erl_eval.6.13229925>
 
  2> scutil:call_after(1000, Dbl, [3]).
  {ok,spawned_worker,<0.3810.0>}
 
  3> scutil:receive_one().
  {item,{call_after_result,6}}
 
  4> Receiver = fun() -> io:format("Listening.~n"), receive X -> io:format("Got ~p~n", [X]), ok end end.
  #Fun<erl_eval.20.67289768>
 
  5> R = spawn(Receiver).
  Listening.
  <0.3817.0>
 
  6> scutil:call_after(1000, Dbl, [3], {handler, R}).
  {ok,spawned_worker,<0.3829.0>}
  Got {call_after_result,6}

Introduced in: Version 26

central_moment/2

central_moment(List::list(), N::integer()) -> float()

Statistics Takes the Nth cetral moment of a list. The Nth central moment of a list is the arithmetic mean of (the list items each minus the mean of the list, each taken to the Nth power). In a sense, this is the "normalized" moment. Fractional Ns are not defined. Not to be confused with moment/2. Thanks to Kraln and Chile for straightening me out on moments and central moments.

  1> scutil:central_moment([1,1,1], 2).
  0.0
 
  2> scutil:central_moment([2,2,2], 2).
  0.0
 
  3> scutil:central_moment([1,2,3], 2).
  0.666666666666666
 
  4> scutil:central_moment([1,2,3], 3).
  0.0

Introduced in: Version 50

central_moments/1

central_moments(List) -> any()

Equivalent to [central_moment(List, N) || N <- [2, 3, 4]].

central_moments/2

central_moments(List, Moments) -> any()

Equivalent to [central_moment(List, N) || N <- Moments].

centroid/1

centroid(InputList::coord_list()) -> coord()

Statistics Calculates the coordinate which represents the per-axis arithmetic mean of a set of points. To calculate the centroid of [1,1], [2,3], you gather the X coordinates [1,2], then use their mean 1.5; then do the same for the Y, [1,3] to 2. The centroid would thus be [1.5,2]. You may pass any number of coordinates to this function, of any axis count, but they must all be the same axis count. The return value will be a coordinate with the same axis count. Negative and real values are fine; imaginary math is not implemented.

  1> scutil:centroid([[1]]).
  [1.0]
 
  2> scutil:centroid([[1,1],[2,2]]).
  [1.5,1.5]
 
  3> scutil:centroid([[1,1,1],[2,2,2],[3,3,3]]).
  [2.0,2.0,2.0]
 
  4> scutil:centroid([[1,-1,1.0],[-2,-2,-2],[3,3,3],[4,4,4],[5,5,5]]).
  [2.2,1.8,2.2]

Introduced in: Version 118

combinations/2

combinations(Items::list(), OutputItemSize::positive_integer()) -> list_of_lists()

List Provides a list of every unique combination of input terms, order-ignorant; contrast permute/2. Permutations are all unique combinations of a set of tokens; the 2-permutations of [a,b,c] for example are [a,b], [a,c] and [b,c]. Note the absence of other orderings, such as [b,a], which are provided by permute/2. Combinations are taken of a smaller count of tokens than the main set. Combinations are not ordered, but this implementation happens to provide answers in the same order as the input list. Mixed-type lists are safe; items are shallow evaluated, meaning that sublists within the list are treated as single elements, and will neither be rearranged nor will have elements selected from within them.

  1> scutil:combinations([a,b,c,d],2).
  [[a,b],[a,c],[a,d],[b,c],[b,d],[c,d]]
 
  2> scutil:combinations(["dave","kate","pat"],2).
  [["dave","kate"],["dave","pat"],["kate","pat"]]
 
  3> scutil:combinations([fast, strong, smart, lucky], 2).
  [[fast,strong], [fast,smart], [fast,lucky], [strong,smart], [strong,lucky], [smart,lucky]]
Thanks to Alisdair Sullivan for this implementation, which has been slightly but not significantly modified since receipt.

Introduced in: Version 89

count_bits/1

count_bits(Number::non_negative_integer()) -> non_negative_integer()

Utility Counts the number of bits turned on in a sufficiently sized unsigned two's compliment integer representation of Num.

  1> scutil:count_bits(5).
  2

Introduced in: Version 9

count_of/2

count_of(Item::any(), List::list()) -> non_negative_integer()

Counts the number of instances of Item in List.

  1> TestData = lists:duplicate(40,[healthy,nonsmoker]) ++ lists:duplicate(10,[healthy,smoker]) ++ lists:duplicate(7,[cancer,nonsmoker]) ++ lists:duplicate(3,[cancer,smoker]).
  [[healthy,nonsmoker], [healthy,nonsmoker], [healthy|...], [...]|...]
 
  2> scutil:count_of([healthy,smoker], TestData).
  10
 
  3> scutil:count_of([healthy,nonsmoker], TestData).
  40

Introduced in: Version 117

counter/1

counter(Name::any()) -> number()

Counters Checks a counter's value; if the counter was not already defined, it will report zero.

  1> scutil:counter(hello).
  0
 
  2> scutil:inc_counter(hello).
  1
 
  3> scutil:inc_counter(hello).
  2
 
  4> scutil:inc_counter(hello).
  3
 
  5> scutil:counter(hello).
  3
 
  6> scutil:reset_counter(hello).
  0
 
  7> scutil:counter(hello).
  0

Introduced in: Version 54

cross_product/2

cross_product(VX::three_vector(), VY::three_vector()) -> three_vector()

Math Incomplete Calculates the cross product of two vectors (Incomplete represented as three_vector()s - no support yet for seven).

  1> scutil:dot_product([1,1,1],[2,2,2]).
  6
 
  2> scutil:dot_product([1,1,1],[3,3,3]).
  9
 
  3> scutil:dot_product([-1,0,1],[3,3,3]).
  0
 
  4> scutil:dot_product([-1,1,1],[3,3,3]).
  3
 
  5> scutil:dot_product([0.5,1,2],[1,1,1]).
  3.5
TODO: Implement seven-dimensional cross product

Introduced in: Version 80

dec_counter/1

dec_counter(Name) -> any()

Equivalent to adjust_counter(Name, -1).

dec_counter/2

dec_counter(Name, By) -> any()

Equivalent to adjust_counter(Name, -1 * By).

diff_timestamp/2

diff_timestamp(A::timestamp(), B::timestamp()) -> float()

Utility Returns the difference, in seconds as a float, between two erlang timestamps as returned by erlang:now(). Negative differences are returned if the latter timestamp B is earlier than the former timestamp A.

  1> A = now().
  {1232,947675,340000}
 
  2> B = now().
  {1232,947679,412000}
 
  3> scutil:diff_timestamp(A,B).
  4.072
 
  4> scutil:diff_timestamp(B,A).
  -4.072

Introduced in: Version 9

dot_product/2

dot_product(VX::numeric_list(), VY::numeric_list()) -> number()

Math Incomplete Calculates the dot product of two vectors (Incomplete represented as numeric lists; tuples not yet supported).

  1> scutil:dot_product([1,1,1],[2,2,2]).
  6
 
  2> scutil:dot_product([1,1,1],[3,3,3]).
  9
 
  3> scutil:dot_product([-1,0,1],[3,3,3]).
  0
 
  4> scutil:dot_product([-1,1,1],[3,3,3]).
  3
 
  5> scutil:dot_product([0.5,1,2],[1,1,1]).
  3.5
TODO: The tuple variation of vectors has not yet been implemented in this function.

Introduced in: Version 80

elements/2

elements(Config, Requested) -> any()

elements/3

elements(Config, Requested, KeyIdx) -> any()

elements/4

elements(Config, Requested, KeyIdx, X4) -> any()

euclidean_distance/2

euclidean_distance(Coordinate1::coord(), Coordinate2::coord()) -> number()

Math Returns the distance between two coordinates in any N-space. In two dimensions, this is known as the Pythagorean theorem. The coordinates may be of any positive integer dimensionality (2d, 3d, but no -1d or 2.5d), but both coordinates must be of the same dimensionality. The coordinates may have real-valued or negative components, but imaginary math is not implemented. This function tolerates tuple coordinates by converting them to lists; list coordinates are thus slightly faster.

  1> scutil:euclidean_distance([0,0],[1,1]).
  1.4142135623730951
 
  2> scutil:euclidean_distance({0,0},[-1,1.0]).
  1.4142135623730951
 
  3> scutil:euclidean_distance([0,0,0,0],[1,-1,1,-1]).
  2.0

Introduced in: Version 108

even_or_odd/1

even_or_odd(Num::integer()) -> even | odd

Documentary Documentary convenience function that returns the atoms even or odd for any integer.

  1> scutil:even_or_odd(3).
  odd

Introduced in: Version 8

every_flag_representation/1

every_flag_representation(Flags::list()) -> list_of_lists()

Lists Returns every interpretation of the list as a set of boolean flags, including all-off and all-on.

  1> scutil:every_flag_representation([1,2,3,4]).
  [ [], [4], [3], [3,4], [2], [2,4], [2,3], [2,3,4], [1], [1,4], [1,3], [1,3,4], [1,2], [1,2,4], [1,2,3], [1,2,3,4] ]
 
  2> length(scutil:every_flag_representation(lists:seq(1,16))).
  65536
 
  3> SourceOfPowers = scutil:every_flag_representation([magic,technology,evil,alien]).
  [[],                              % Batman
   [alien],                         % Superman
   [evil],                          % Darkseid
   [evil,alien],                    % Sinestro
   [technology],                    % Mister Terrific (Michael Holt)
   [technology,alien],              % The Blue Beetle
   [technology,evil],               % The OMACs
   [technology,evil,alien],         % Braniac
   [magic],                         % Shazam
   [magic,alien],                   % Green Lantern (Alan Scott)
   [magic,evil],                    % Lucifer Morningstar
   [magic,evil,alien],              % pre-crisis Star Sapphire
   [magic,technology],              % Alexander Luthor Jr.
   [magic,technology,alien],        % Mister Miracle
   [magic,technology,evil],         % pre-crisis Sinestro
   [magic,technology,evil,alien]]   % Granny Goodness

Introduced in: Version 126

every_member_representation/1

every_member_representation(Memberships) -> any()

Equivalent to every_member_representation(Memberships, no_absence).

every_member_representation/2

every_member_representation(Memberships::list_of_lists(), AllowAbsence::atom()) -> list_of_lists()

Introduced in: Version 126

expand_label/1

expand_label(X1) -> any()

expand_labels/1

expand_labels(List) -> any()

f32_iolist_to_int/1

f32_iolist_to_int(X1) -> any()

Equivalent to f32_iolist_to_int(A, B, C, D, little).

f32_iolist_to_int/2

f32_iolist_to_int(X1, X2) -> any()

Equivalent to f32_iolist_to_int(A, B, C, D, Endianness).

f32_iolist_to_int/4

f32_iolist_to_int(A, B, C, D) -> any()

Equivalent to f32_iolist_to_int(A, B, C, D, little).

f32_iolist_to_int/5

f32_iolist_to_int(A, B, C, D, X5) -> any()

flesch_kincaid_readability/4

flesch_kincaid_readability(Data, WordCounter, SentenceCounter, SyllableCounter) -> any()

Introduced in: Version 131

flesch_kincaid_readability_score/3

flesch_kincaid_readability_score(Words, Sentences, Syllables) -> any()

Introduced in: Version 131

float_to_f32_iolist/1

float_to_f32_iolist(X) -> any()

float_to_f32_iolist/2

float_to_f32_iolist(X, X2) -> any()

geometric_mean/1

geometric_mean(InputList::numericlist()) -> float()

Statistics Take the geometric mean of a list of numbers.

  1> scutil:geometric_mean([1,2,3,4,5]).
  2.6051710846973517
The naive approach
  geometric_mean(List) -> math:pow(scutil:list_product(List), 1/length(List)).
is not used because it accumulates error very quickly, and is as such unsuited to huge lists.

Introduced in: Version 34

See also: arithmetic_mean/1, gmean_vector_normal/1, harmonic_mean/1.

get_module_attribute/1

get_module_attribute(Module::atom()) -> AttributeList | {error, no_such_module}

Utility Look up all attributes of a given module.

  1> scutil:get_module_attribute(scutil).
  [{author,"John Haugeland <stonecypher@gmail.com>"},
   {bugtracker,"http://crunchyd.com/forum/project.php?projectid=7"},
   {currentsource,"http://crunchyd.com/release/scutil.zip"},
   {description,"StoneCypher's utility library."},
   {library_requirements,[{testerl,16}]},
   {license,[{mit_license,"http://scutil.com/license.html"}]},
   {publicforum,"http://crunchyd.com/forum/scutil-discussion/"},
   {publicsvn,"svn://crunchyd.com/scutil/"},
   {svn_head,"$HeadURL: svn://crunchyd.com/scutil/scutil.erl $"},
   {svn_id,"$Id: scutil.erl 137 2009-02-27 02:54:58Z john $"},
   {svn_revision,"$Revision: 137 $"},
   {testerl_export,[{[],scutil_testsuite}]},
   {vsn,[134633400955530778836494569152232539093]},
   {webpage,"http://scutil.com/"}]

Introduced in: Version 129

get_module_attribute/2

get_module_attribute(Module::atom(), Attribute::atom()) -> {value, {Attribute, Value}} | {error, no_such_attribute} | {error, no_such_module}

Utility Buggy Look up an Erlang module attribute value by title. Originally found at Mastering Erlang Part 3; subsequently cleaned up and given error reporting.

  1> scutil:get_module_attribute(scutil, author).
  "John Haugeland <stonecypher@gmail.com>"
 
  2> scutil:get_module_attribute(scutil, license).
  [{mit_license,"http://scutil.com/license.html"}]
Thanks to Alain O'Dea for pointing out defects in this routine regarding repeated module elements, and available improvements to the provided API. Mr. O'Dea's insightful advice will be implemented, but that time has not yet come.

Introduced in: Version 23

get_module_feature/2

get_module_feature(Module, Feature) -> any()

gmean_vector_normal/1

gmean_vector_normal(VX::numeric_list()) -> number()

Statistics Returns the geometric mean of the elements of the unit vector for the vector provided.

Introduced in: Version 85

grid_scatter/2

grid_scatter(Count::integer(), Size::gridsize()) -> coordlist()

Random Return a Count-length list of non-repeating coordinates in a grid of specified size; useful for feature generation.

Introduced in: Version 42

harmonic_mean/1

harmonic_mean(InputList::numericlist()) -> float()

Statistics Take the harmonic mean of a list of numbers.

  1> scutil:harmonic_mean([1,2,3,4,5]).
  2.18978102189781

Introduced in: Version 35

See also: arithmetic_mean/1, geometric_mean/1, hmean_vector_normal/1.

has_bit/2

has_bit(Number::non_negative_integer(), Bit::non_negative_integer()) -> true | false

Utility Checks whether a given bit is on in a sufficiently sized unsigned two's compliment integer representation of Num.

  1> scutil:has_bit(5,0).
  true
 
  2> scutil:has_bit(5,1).
  false

Introduced in: Version 9

has_note/2

has_note(Notebook::filename(), NoteName::any()) -> true | false | {error, E}

Persistence Checks if a given note exists in a given notebook, returning boolean atoms as an answer. Checking whether a note exists in a missing notebook is considered an error. DETS opening and closing are automatically managed.

Introduced in: Version 83

has_notebook/1

has_notebook(Notebook::filename()) -> true | false

Persistence Returns a boolean true or false whether a notebook under a given filename already exists. Does not attempt to create the notebook under any circumstances.

Introduced in: Version 83

hex_to_int/1

hex_to_int(HexChar::hexstring() | hexchar()) -> integer()

Conversion Convert a hexstring() or hexchar() into its numeric value.

  1> scutil:hex_to_int("c0ffEE").
  12648430
 
  2> scutil:hex_to_int($e).
  14
 
  3> scutil:hex_to_int("100").
  256

Introduced in: Version 18

histograph/1

histograph(List::list()) -> weightlist()

Statistics Takes a histograph count of the items in the list. Mixed type lists are safe. Input lists do not need to be sorted. The histograph is shallow - that is, the histograph of [ [1,2], [1,2], [2,2] ] is [ {[1,2],2}, {[2,2],1} ], not [ {1,2}, {2,4} ].

  1> scutil:histograph([1,2,a,2,b,1,b,1,b,2,a,2,2,1]).
  [{1,4},{2,5},{a,2},{b,3}]
 
  2> scutil:histograph([ scutil:rand(10) || X <- lists:seq(1,100000) ]).
  [{0,10044}, {1,9892}, {2,10009}, {3,10016}, {4,10050}, {5,10113}, {6,9990}, {7,9994}, {8,10004}, {9,9888}]

Introduced in: Version 19

hmean_vector_normal/1

hmean_vector_normal(VX::numeric_list()) -> number()

Statistics Returns the harmonic mean of the elements of the unit vector for the vector provided.

Introduced in: Version 85

implode/2

implode(Separator, Data) -> any()

inc_counter/1

inc_counter(Name) -> any()

Equivalent to adjust_counter(Name, 1).

inc_counter/2

inc_counter(Name, By) -> any()

Equivalent to adjust_counter(Name, By).

int_to_u32_iolist/1

int_to_u32_iolist(X) -> any()

Equivalent to int_to_u32_iolist(X, little).

int_to_u32_iolist/2

int_to_u32_iolist(X, X2) -> any()

int_to_u64_iolist/1

int_to_u64_iolist(X) -> any()

Equivalent to int_to_u64_iolist(X, little).

int_to_u64_iolist/2

int_to_u64_iolist(X, X2) -> any()

interpret_flesch_kincaid_readability_score/1

interpret_flesch_kincaid_readability_score(R) -> any()

Introduced in: Version 131

io_list_to_hex/1

io_list_to_hex(Input::io_list()) -> hexstring()

Conversion Convert an io_list() to a hexstring().

  1> scutil:io_list_to_hex("a").
  "61"
 
  2> scutil:io_list_to_hex("a08n408nbqa").
  "6130386e3430386e627161"

Introduced in: Version 19

isolate_signal/1

isolate_signal(Waveform) -> any()

Introduced in: Version 129

kendall_correlation/1

kendall_correlation(TupleList::coordlist()) -> {tau, Correlation::number()}

Statistics Compute the Kendall Tau Rank Correlation Coefficient of a list of coordinate tuples.

  1> scutil:kendall_correlation([ {1,1}, {2,2}, {3,3}, {4,4}, {5,5} ]).
  {tau,1.0}
 
  2> scutil:kendall_correlation([ {1,5}, {2,4}, {3,3}, {4,2}, {5,1} ]).
  {tau,-1.0}
 
  3> scutil:kendall_correlation([ {1,3}, {2,3}, {3,3}, {4,3}, {5,3} ]).
  {tau,1.0}
 
  4> scutil:kendall_correlation([ {1,2}, {2,2.5}, {3,3}, {4,3.5}, {5,4} ]).
  {tau,1.0}
 
  5> scutil:kendall_correlation([ {1,2}, {2,2.4}, {3,3}, {4,3.6}, {5,4} ]).
  {tau,1.0}

Introduced in: Version 51

kendall_correlation/2

kendall_correlation(List1, List2) -> any()

Equivalent to kendall_correlation(lists:zip(List1, List2)).

kurtosis/1

kurtosis(List) -> any()

Equivalent to central_moment(List, 4).

list_intersection/2

list_intersection(List1, List2) -> any()

Equivalent to list_intersection(List1, List2, unsorted).

list_intersection/3

list_intersection(List1::list(), List2::list(), IsSorted::atom()) -> list()

Efficiently computes the intersection of two lists. The third parameter, which is optional and defaults to unsorted, is either the atom sorted or unsorted. If sorted is used, the function will sort both inputs before proceeding, as it requires sorted lists; as such, if you already know your lists to be sorted, passing unsorted will save some time. The return list will be reverse sorted.

  1> scutil:list_intersection([1,2,3,4,5,2,3,10,15,25,30,40,45,55],[1,3,5,5,5,15,20,30,35,40,50,55]).
  [55,40,30,15,5,3,1]
 
  2> scutil:list_intersection([1],[2]).
  []
Thanks to Ayrnieu for catching a defect in the initial implementation.

Introduced in: Version 120

list_product/1

list_product(A::numericlist()) -> number()

Math Takes the product of all numbers in the list. Offered mostly to make dependant code clearer.

  1> scutil:list_product([1,2,5.4]).
  10.8

Introduced in: Version 39

list_to_number/1

list_to_number(X::list()) -> number()

Conversion Converts a list into a number; integers will be returned if there is no mantissa in the list representation.

  1> scutil:list_to_number("2").
  2
 
  2> scutil:list_to_number("2.0").
  2.0
 
  3> scutil:list_to_number("2.1").
  2.1

Introduced in: Version 8

make_notebook/1

make_notebook(Notebook::filename()) -> ok | {error, E}

Persistence (Called automatically) Creates a "notebook", which is just a convenience wrapped DETS set table.

Introduced in: Version 83

map_reduce/2

map_reduce(Function, Workload) -> any()

Equivalent to map_reduce(Function, Workload, 1, nodes()).

map_reduce/3

map_reduce(Function, Workload, JobsPerNode) -> any()

Equivalent to map_reduce(Function, Workload, JobsPerNode, nodes()).

map_reduce/4

map_reduce(Function::function(), Workload::list(), JobsPerNode::positive_integer(), Nodes::list()) -> list()

Parallelism Takes a workload, a function, a count of jobs per node and a node list, and distributes work on demand to available nodes until fulfilled. Results are provided in the order the workload was provided, regardless of in what order they are completed or received.

TODO: add crash handling behavior, progress querying behavior

median/1

median(List::numericlist()) -> any()

Statistics Takes the median (central) value of a list. Sorts the input list, then finds and returns the middle value.

  1> scutil:median([1,2,999]).
  2

Introduced in: Version 8

See also: arithmetic_mean/1, mode/1.

median_absolute_deviation/1

median_absolute_deviation(List::numericlist()) -> number()

Statistics Calculate the median absolute deviation of a numericlist().

  1> scutil:median_absolute_deviation([1,1,2,2,4,6,9]).
  1

Introduced in: Version 81

minmax/1

minmax(RestOfList) -> any()

Introduced in: Version 129

mod/2

mod(Base::integer(), Range::integer()) -> integer()

Math Takes the modulus of an integer by another integer. Luckily, erlang calls what most languages refer to as modulus by its correct name, remainder (c's %, erlang's rem). Modulus is implemented incorrectly in nearly every language, because chip vendors implement remainder and the wrong name stuck. The difference is in how the operator reacts to a negative Base: -10 modulo 3 is 2, whereas -10 rem 3 is -1. Remainder takes the residue of dividing the base by the lowest (nearest negative infinity) integer N adjacent the real valued divisor; modulo returns the highest, which is less CPU efficient but always provides an answer on [0..Range-1].

  1> scutil:mod(10,3).
  1
 
  2> [ scutil:mod(X,4) || X <- lists:seq(-10,10) ].
  [2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2]

Introduced in: Version 29

mode/1

mode(List::numericlist()) -> any()

Statistics Takes the mode (most common) value(s) of a list, as a list. If there are more than one value tied for most common, all tied will be returned. This function is safe for mixed-type lists, and does not perform deep traversal (that is, the mode of [ [2,2] ] is [2,2], not 2).

  scutil:mode([1,2,1,3,1,4]).
  [1]
 
  2> scutil:mode([ [1,2,3], [2,3,4], [3,4,5], [2,3,4] ]).
  [[2,3,4]]
 
  3> scutil:mode([ a,b, 1, a,b, 2, a,b, 3 ]).
  [a,b]

Introduced in: Version 8

See also: arithmetic_mean/1, median/1.

module_abstract_code/1

module_abstract_code(Module) -> any()

Introduced in: Version 130

module_atoms/1

module_atoms(Module) -> any()

Introduced in: Version 130

module_has_function/2

module_has_function(Module, Function) -> any()

moment/2

moment(List::list(), N::number()) -> float()

Statistics Takes the Nth moment of a list. The Nth moment of a list is the arithmetic mean of the list items, each taken to the Nth power. Fractional Ns are well defined and have obscure uses, though most will only ever use this with integer values of N; this function is valid for both. Not to be confused with central_moment/2. Thanks to Kraln and Chile for straightening me out on moments and central moments.

  1> scutil:moment([1,1,1], 2).
  1.0
 
  2> scutil:moment([2,2,2], 2).
  4.0
 
  3> scutil:moment([1,2,3], 2).
  4.666666666666667
 
  4> scutil:moment([1,2,3], 3).
  12.0
 
  5> scutil:moment([1,2,3], 3.5).
  19.693026767781483

Introduced in: Version 50

moments/1

moments(List) -> any()

Equivalent to [moment(List, N) || N <- [2, 3, 4]].

moments/2

moments(List, Moments) -> any()

Equivalent to [moment(List, N) || N <- Moments].

multi_do/3

multi_do(C, Module, Func) -> any()

Equivalent to multi_do(C, M, F, []).

Introduced in: Version 38

multi_do/4

multi_do(Count::integer(), Module::atom(), Function::atom(), Args::list()) -> list()

Serialism Take an iteration count, a module name, a function name and an argument list, and repeatedly apply the argument list to the module/function, count times. This is primarily useful with nondeterministic functions whose result might change despite identical arguments, such as functions with random behavior; for example, this function is invoked to implement stochastic testing in TestErl.

  1> scutil:multi_do(10, scutil, rand, [100]).
  [9,94,4,82,77,44,89,19,45,92]
 
  2> scutil:multi_do(10, scutil, rand, [10000]).
  [2377,2559,1713,8489,4468,3261,3344,3751,380,2525]

Introduced in: Version 38

normalize_vector/1

normalize_vector(Vector::vector()) -> unit_vector()

Math Returns the magnitude of a vector. A vector's magnitude is the length of its hypoteneuse. A vector can be seen as the product of its unit vector and its magnitude; as such many people see a vector's magnitude as its scale. The normal of the zero vector is undefined, in the way that dividing by zero is undefined, and will throw an arithmetic exception.

  1> scutil:normalize_vector([0,3,4]).
  [0.0,0.6,0.8]
TODO: When tuple comprehensions are introduced to the language, convert this to using them.

Introduced in: Version 85

nybble_to_hex/1

nybble_to_hex(Nyb::nybble()) -> integer()

Conversion Convert a nybble() to a hexchar().

  1> scutil:nybble_to_hex(7).
  55
 
  2> scutil:nybble_to_hex(15).
  102

Introduced in: Version 19

ordered_ranks_of/1

ordered_ranks_of(Values::numericlist()) -> rankinglist()

Statistics Returns a tied ranked ordering of the list, ordered according to the input ordering rather than the sorted ordering. As with tied_ranks_of/1, all rankings are floats, and ties are represented as the centers of ranges.

  1> scutil:ordered_ranks_of([10,90,20,80,30,70,40,60,50]).
  [{9.0,10}, {1.0,90}, {8.0,20}, {2.0,80}, {7.0,30}, {3.0,70}, {6.0,40}, {4.0,60}, {5.0,50}]
 
  2> scutil:ordered_ranks_of([100,200,200,300]).
  [{4.0,100},{2.5,200},{2.5,200},{1.0,300}]

Introduced in: Version 42

pearson_correlation/1

pearson_correlation(TupleList::coordlist()) -> {r, Correlation::number()}

Statistics Compute the Pearson Correlation Coefficient of a list of coordinate tuples.

  1> scutil:pearson_correlation([ {1,1}, {2,2}, {3,3}, {4,4}, {5,5} ]).
  {r,1.0}
 
  2> scutil:pearson_correlation([ {1,5}, {2,4}, {3,3}, {4,2}, {5,1} ]).
  {r,-1.0}
 
  3> scutil:pearson_correlation([ {1,3}, {2,3}, {3,3}, {4,3}, {5,3} ]).
  {r,0.0}
 
  4> scutil:pearson_correlation([ {1,2}, {2,2.5}, {3,3}, {4,3.5}, {5,4} ]).
  {r,1.0}
 
  5> scutil:pearson_correlation([ {1,2}, {2,2.4}, {3,3}, {4,3.6}, {5,4} ]).
  {r,0.9970544855015818}

Introduced in: Version 49

pearson_correlation/2

pearson_correlation(List1, List2) -> any()

Equivalent to pearson_correlation(lists:zip(List1, List2)).

permute/1

permute(List) -> any()

Equivalent to permute(List, length(List)).

permute/2

permute(List::list(), Depth::positive_integer()) -> list()

Utility Calculate either the full or the depth-limited permutations of a list, order sensitive; contrast combinations/2. Permutations are all valid orderings of a set of tokens; the permutations of [a,b] for example are [a,b] and [b,a]. Depth limitation means the permutations of a smaller count of tokens from the main set; the 2-limited permutations of [a,b,c] for example are [a,b], [a,c], [b,a], [b,c], [c,a] and [c,b]. Permutations are not ordered. Mixed-type lists are safe; items are shallow evaluated, meaning that sublists within the list are treated as single elements, and will neither be rearranged nor will have elements selected from within them.

  1> scutil:permute(["dave","kate","pat"]).
  [{"pat","kate","dave"}, {"kate","pat","dave"}, {"pat","dave","kate"}, {"dave","pat","kate"}, {"kate","dave","pat"}, {"dave","kate","pat"}]
 
  2> scutil:permute([fast, strong, smart, lucky], 2).
  [{strong,fast}, {smart,fast}, {lucky,fast}, {fast,strong}, {smart,strong}, {lucky,strong}, {fast,smart}, {strong,smart}, {lucky,smart}, {fast,lucky}, {strong,lucky}, {smart,lucky}]

Introduced in: Version 17

qsp_average/2

qsp_average(W::numericlist(), InputVecs::vectorlist()) -> float()

Math Takes the quadratic scalar product average of a vector W and a list of vectors X. The QSP Average is the arithmetic mean of the result set Y, where Y is generated as the square of the magnitude of the dot product of W and each individual vector in X.

  1> scutil:qsp_average([1,2,3], [[0,0,0],[0,0,0]]).
  0.0
 
  2> scutil:qsp_average([1,2,3], [[0,0,1],[0,0,0]]).
  4.5
 
  3> scutil:qsp_average([1,2,3], [[0,1,0],[0,0,0]]).
  2.0
 
  4> scutil:qsp_average([1,2,3], [[1,0,0],[0,0,0]]).
  0.5
 
  5> scutil:qsp_average([1,2,3], [[1,1,1],[0,0,0]]).
  18.0
 
  6> scutil:qsp_average([1,2,3], [[0,0,0],[1,1,1]]).
  18.0
 
  7> scutil:qsp_average([1,2,3], [[1,1,1],[1,1,1]]).
  36.0
The linked documentation incorrectly uses the notation ||Foo|| instead of |Foo| to present the algorithm. ||Foo|| is the vector magnitude - the root sum square of vector elements - but as the input is the dot product of two 1d vectors, which will always be a single number, the vector magnitude serves no purpose other than to normalize the sign slowly and counterintuitively; thus we switch to abs despite the documentation. Thanks to Steve Stair for helping straighten this out.

Introduced in: Version 82

rand/1

rand(Range::integer()) -> integer()

Random Returns a pseudorandom integer on the range [0 - (Range-1)] inclusive.

  1> scutil:rand(100).
  9
 
  2> [ scutil:rand(100) || X <- lists:seq(1,10) ].
  [12,27,99,86,20,96,28,36,28,15]
 
  3> scutil:histograph([ scutil:rand(10) || X <- lists:seq(1,10000) ]).
  [{0,992}, {1,990}, {2,992}, {3,1033}, {4,1017}, {5,1003}, {6,996}, {7,1024}, {8,969}, {9,984}]
 
  4> scutil:histograph([ scutil:rand(10) || X <- lists:seq(1,10000) ]).
  [{0,1028}, {1,979}, {2,934}, {3,970}, {4,1035}, {5,1007}, {6,986}, {7,1012}, {8,1052}, {9,997}]

Introduced in: Version 5

random_from/1

random_from(List) -> any()

Equivalent to random_from(1, List, no_remainder).

Introduced in: Version 6

random_from/2

random_from(N, List) -> any()

Equivalent to random_from(N, List, no_remainder).

Introduced in: Version 6

random_from/3

random_from(N::integer(), List::list(), WantRemainder::want_remainder()) -> list()

Random Take N non-repeating random elements from a list in undefined order. If the atom remainder is passed in as the third argument, the unused portion of the source list will be returned as the second member of a 2ary tuple with the results; the default is no_remainder, which only returns the result set. Mixed type input lists are perfectly safe, and membership for random selection is shallow (ie, [ [1,2], [3,4] ] as an input list would only generate outputs of lists, never integers.)

  1> scutil:random_from([monday,tuesday,wednesday,thursday,friday]).
  friday
 
  2> scutil:random_from(4, lists:seq(1,20)).
  [6,3,15,12]
 
  3> scutil:random_from(3, [warrior, mage, cleric, thief, paladin, ranger, bard]).
  [cleric,warrior,ranger]
 
  4> scutil:random_from(6, [mixed, [1,2,3], 4, {five,5}, 3, 67.2, <<"Hello">>, 8]).
  [[1,2,3],{five,5},4,mixed,<<"Hello">>,67.2]
 
  5> {Team1, Team2} = scutil:random_from(3, [alice,bob,cathy,dave,edward,fawn], remainder).
  {[cathy,fawn,dave],[bob,edward,alice]}
 
  6> Team1.
  [cathy,fawn,dave]
 
  7> Where_Food = fun() -> scutil:random_from([deli, fastfood, chinese, mexican, steakhouse, bistro, greek, indian, thai, sushi]) end.
  #Fun<erl_eval.20.67289768>
 
  8> Where_Food().
  thai

Introduced in: Version 6

random_from_weighted/1

random_from_weighted(InputList::weightlist()) -> any()

Random Take a random single item from a list with weighted probabilities. Probabilities may be any numeric type, and may be any non-negative value (items with zero probability will be omitted). Input is a weightlist(), which is a list in the form [{Item,Probability}, {I2,P2}, ...]. There is no requirement to normalize probabilities to any range, though probabilities normalized to ranges will still work as expected.

  1> scutil:random_from([ {quad,4}, {double,2}, {single,1} ]).
  quad
 
  2> [ scutil:random_from_weighted([ {quad,4}, {double,2}, {single,1} ]) || X <- lists:seq(1,10) ].
  [single,quad,quad,double,quad,double,quad,quad,quad,double]
 
  3> scutil:histograph([ scutil:random_from_weighted([ {quad,4}, {double,2}, {single,1} ]) || X <- lists:seq(1,777777) ]).
  [{double,222200},{quad,444165},{single,111412}]

Introduced in: Version 10

ranks_of/1

ranks_of(Values::numericlist()) -> rankinglist()

Statistics Returns a ranked ordering of the list without tie rankings.

  1> scutil:ranks_of([10,90,20,80,30,70,40,60,50]).
  [{1,90}, {2,80}, {3,70}, {4,60}, {5,50}, {6,40}, {7,30}, {8,20}, {9,10}]
 
  2> scutil:ranks_of([10,10,10,10]).
  [{1,10},{2,10},{3,10},{4,10}]

Introduced in: Version 42

read_note/2

read_note(Notebook::filename(), NoteName::any()) -> {value, V} | {error, E}

Persistence Read a key/value pair from a notebook file. DETS opening and closing are automatically managed.

Introduced in: Version 83

receive_one/0

receive_one() -> {item, any()} | nothing_there

Utility Pop the front of the message queue and return it as {item,X}, or return nothing_there for empty queues; do not block.

  1> scutil:receive_one().
  nothing_there
 
  2> self() ! message.
  message
 
  3> scutil:receive_one().
  {item,message}
 
  4> scutil:receive_one().
  nothing_there

Introduced in: Version 2

record_member/2

record_member(E::any(), R::record()) -> true | false

TODO: Needs Example Checks whether E is a member element of record R, analogous to lists::member(E, L). This function does not have examples because the shell does not correctly handle records; todo: add examples later

Introduced in: Version 123

regex_read_matches/2

regex_read_matches(String, Reg) -> any()

Equivalent to regex_read_matches(String, Reg, {0, 0}).

Introduced in: Version 41

regex_read_matches/3

regex_read_matches(String::string(), Reg::string(), X3::{TrimFront::integer(), TrimLength::integer()}) -> list() | {error, E}

Regex Take a string and a regular expression (and optionally an offset and length to trim to in each result), and return a list of all matches. For a trim length of {A,B}, the first A and last B characters of each result will be removed.

  1> scutil:regex_read_matches("0j2  4g5  8t9", "[0-9](.)[0-9]").
  ["0j2","4g5","8t9"]
 
  2> scutil:regex_read_matches("0j2  4g5  8t9", "[0-9](.)[0-9]", {1,1}).
  ["j","g","t"]
 
  3> scutil:regex_read_matches("0j2  4g5  8t9", "[0-9](.)[0-9]", 1, 1).
  ["j","g","t"]
Why provide the equivalent syntaxes (_, _, {A,B}) and (_, _, A,B) ? Without the tuple is more natural to many, but with the tuple is far more convenient for database-driven behavior, as well as the internal implementation. I frequently find myself using both forms, and so every time I simplify I find myself wrapping the non-removed form back into the removed form. Does it violate the simplest interface principle? Yeah, but in this case it's a boon, IMO. As such, keeping both forms.

Introduced in: Version 41

regex_read_matches/4

regex_read_matches(String, Reg, TrimFront, TrimLength) -> any()

Equivalent to regex_read_matches(String, Reg, {TrimFront, TrimLength}).

Introduced in: Version 41

remove_note/2

remove_note(Notebook::filename(), NoteName::any()) -> ok | {error, E}

Persistence Removes a note by name from a given notebook. Removing a nonexistant note is considered an error.

Introduced in: Version 83

remove_notebook/1

remove_notebook(Notebook::filename()) -> ok | {error, E}

Persistence Attempts to remove a notebook; all data in the removed notebook is lost permanently.

Introduced in: Version 83

reset_counter/1

reset_counter(Name) -> any()

Equivalent to set_counter(Name, 0).

Introduced in: Version 54

root_mean_square/1

root_mean_square(Values::numericlist()) -> float()

Statistics Calculates the root mean square of the values in the list.

  1> scutil:root_mean_square([1,2,3,4,5]).
  3.3166247903554
 
  2> scutil:root_mean_square([2,2,2]).
  2.0

Introduced in: Version 39

root_sum_square/1

root_sum_square(VX::vector()) -> number()

Math Calculate the magnitude (also known as the root sum square)

Introduced in: Version 85

sanitize_filename/1

sanitize_filename(Filename::string()) -> string()

String Sanitize an arbitrary string to be appropriate for Windows and Unix filesystems, and URLs.

  1> scutil:sanitize_filename("\h/e~l%lo! w^o@r#l*d.").
  "helloworld"

Introduced in: Version 31

See also: sanitize_tokens/2.

sanitize_tokens/2

sanitize_tokens(InputList::list(), Allowed::sanitizer()) -> list()

List Remove unacceptable elements from an input list, as defined by another list or a filter function. Common reasons for sanitization include reducing arbitrary or bulk data to key format (such as using an original filename and new size to generate a new filename or database key) and removing malformed items from a list before processing.

  1> scutil:sanitize_tokens("ae0z4nb'wc-04bn ze0e 0;4ci ;e0o5rn;", "ace").
  "aeceece"
 
  2> Classifier = fun(apple) -> true; (banana) -> true; (cherry) -> true; (date) -> true; (elderberry) -> true; (_) -> false end.
  #Fun<erl_eval.6.13229925>
 
  3> scutil:sanitize_tokens([apple, boat, cherry, dog, elderberry], Classifier).
  [apple,cherry,elderberry]

Introduced in: Version 31

See also: sanitize_filename/1.

scan_svn_revision/1

scan_svn_revision(ModuleName::atom()) -> integer()

Utility Scans a module for an attribute svn_revision, parses it in the format expected from the svn:keyword Revision, and returns the version number as an integer. To use, add a module attribute to your module as follows: -svn_revision("$+Revision$)., after removing the plus (if the plus wasn't there, the example would get corrupted when I updated the module ;)). Then set the svn keyword "Revision" on the file, and check it in. After that, your version is magically updated every time you check in! :D The sole argument to this function is the name of the module to be scanned, as an atom.

  1> scutil:scan_svn_revision(testerl).
  16

Introduced in: Version 44

set_counter/2

set_counter(Name::any(), To::number()) -> 0

Counters Sets a counter's value to a specific value.

  1> scutil:counter(hello).
  0
 
  2> scutil:set_counter(hello,4).
  4
 
  3> scutil:counter(hello).
  4
 
  4> scutil:reset_counter(hello).
  0
 
  5> scutil:counter(hello).
  0

Introduced in: Version 54

shared_keys/1

shared_keys(TupleList) -> any()

shared_keys/2

shared_keys(TupleList::sorted_keylist(), Presorted::presorted) -> sorted_keylist()

Equivalent to shared_keys(lists:zip(lists:sort(A), lists:sort(B))).

Equivalent to shared_keys/1, but skips sorting the lists (and thus requires pre-sorted lists), which may save significant work repetition.

shared_keys/3

shared_keys(A::sorted_keylist(), B::sorted_keylist(), Presorted::presorted) -> sorted_keylist()

Equivalent to shared_keys(lists:sort(A), lists:sort(B)).

Equivalent to shared_keys/2, but skips sorting the lists (and thus requires pre-sorted lists), which may save significant work repetition.

shuffle/1

shuffle(List::list()) -> list()

Random Return a list with the original list's shallow members in a random order. Deep lists are not shuffled; [ [a,b,c], [d,e,f], [g,h,i] ] will never produce sublist reorderings ([b,c,a]) or list mixing ([b,g,e]), only reordering of the three top level lists. The output list will always be the same length as the input list. Repeated items and mixed types in input lists are safe.

  1> scutil:shuffle(lists:seq(1,9)).
  [8,4,7,9,5,2,6,1,3]
 
  2> {TheFaces, TheSuits} = {  [ace] ++ lists:seq(2,10) ++ [jack,queen,king],  [hearts,spades,clubs,diamonds]  }
  {[ace,jack,queen,king,2,3,4,5,6,7,8,9,10],
   [hearts,spades,clubs,diamonds]}
 
  3> Deck = scutil:shuffle([ {Face,Suit} || Face <- TheFaces, Suit <- TheSuits ]).
  [ {6,spades}, {7,hearts}, {8,clubs}, {queen,spades}, {6,diamonds}, {ace,...}, {...} | ...]
 
  4> scutil:shuffle([ duck,duck,duck,duck, goose ]).
  [duck,goose,duck,duck,duck]
Originally found at http://wiki.trapexit.org/index.php/RandomShuffle; refactored for clarity, and unnecessary repeat nesting behavior removed.

Introduced in: Version 8

skewness/1

skewness(List) -> any()

Equivalent to central_moment(List, 3).

spearman_correlation/1

spearman_correlation(TupleList::coordlist()) -> {rsquared, Correlation::number()}

Statistics Compute the Spearman's Rank Correlation Coefficient of a list of coordinate tuples.

  1> scutil:spearman_correlation([ {1,1}, {2,2}, {3,3}, {4,4}, {5,5} ]).
  {rsquared,1.0}
 
  2> scutil:spearman_correlation([ {1,5}, {2,4}, {3,3}, {4,2}, {5,1} ]).
  {rsquared,-1.0}
 
  3> scutil:spearman_correlation([ {1,3}, {2,3}, {3,3}, {4,3}, {5,3} ]).
  {rsquared,0.5}
 
  4> scutil:spearman_correlation([ {1,2}, {2,2.5}, {3,3}, {4,3.5}, {5,4} ]).
  {rsquared,1.0}
 
  5> scutil:spearman_correlation([ {1,2}, {2,2.4}, {3,3}, {4,3.6}, {5,4} ]).
  {rsquared,1.0}

Introduced in: Version 50

spearman_correlation/2

spearman_correlation(List1, List2) -> any()

Equivalent to spearman_correlation(lists:zip(List1, List2)).

square/1

square(Input::number()) -> number()

Math Squares the input; convenient in list comprehensions to prevent recalculation, and clear in the fashion of documentary functions.

  1> scutil:square(2).
  4
 
  2> scutil:square(2.5).
  6.25

Introduced in: Version 108

srand/0

srand() -> {ok, {seeded, Seed}}

Random (Called automatically) Instantiates the random source, destroying a prior source if needed, and seeds the source with the clock, returning the seed used. Generally speaking, you do not need this function; this is used manually when you want to know what seed was used, for purposes of recreating identical pseudorandom sequences. Otherwise, rand() will call this once on its own. Because the scutil random system spawns a utility process to maintain random state, this function should be considered to have side effects for purposes of testing. (Indeed, in a sense, this function's entire purpose is to cause a side effect.)

  1> scutil:srand().
  {ok,{seeded,{1227,902172,685000}}}
 
  2> scutil:srand().
  {ok,{seeded,{1227,902173,231000}}}

Introduced in: Version 5

srand/3

srand(A::integer(), B::integer(), C::integer()) -> {ok, {seeded, Seed}}

Random (Called automatically) Instantiates the random source, destroying a prior source if needed, and seeds the source with the three integer seed you provide, returning the seed used. Generally speaking, you do not need this function; this is used manually when you want set what seed is used, for purposes of recreating identical pseudorandom sequences. Otherwise, rand() will call this once on its own. Because the scutil random system spawns a utility process to maintain random state, this function should be considered to have side effects for purposes of testing. (Indeed, in a sense, this function's entire purpose is to cause a side effect.)

  1> scutil:srand(1,2,3).
  {ok,{seeded,{1,2,3}}}
 
  2> scutil:srand().
  {ok,{seeded,{1227,902568,604600}}}
 
  3> scutil:srand(1,2,3).
  {ok,{seeded,{1,2,3}}}

Introduced in: Version 5

standard_listener/3

standard_listener(Handler, Port, SocketOptions) -> {ok, WorkerPid, ListeningPort} | {error, E}

Network Listens on a socket and manages the fast packet loss problem.

There is a defect in the canonical listener, where under extreme load a packet could be delivered before the socket has been traded off to the handler process. This would mean that the socket could deliver one (or, theoretically, more) packets to the wrong process. {active,false} is immune to this problem, but very inconvenient and in some ways against the erlang mindset.

standard_listener resolves the default {active,true} into the configuration if missing, then if active is not {active,false}, strips the active status out, handles the socket {active,false}, then passes to an internal handling function which re-engages the expected active status (erlang sockets when switched to active true or once immediately deliver their backlogs), and passes off to the user specified handler which receives its expected behavior without change. (Also, this takes some of the repeat grunt work out of making listeners.)

The function in Handler should be a 2-ary function which accepts a socket and the list of options the socket used, augmented with the tuple {from_port,Port}, where Port is the listening port from which the connection was accepted.TODO: Needs code example

Thanks to MisterN for counsel, noticing several embarrassing bugs, and challenging me to refine my approach from several directions. Thanks to Steve Vinoski for pointing out that I'd neglected to set the controlling process, that the port closed signal was not being caught, and that ephemeral ports could nicely be supported by opening port 0 then reporting the listening port.

Introduced in: Version 96

start_register_if_not_running/3

start_register_if_not_running(Name, Module, Function) -> any()

Equivalent to start_register_if_not_running(node(), Name, Module, Function, []).

start_register_if_not_running/4

start_register_if_not_running(Name, Module, Function, Args) -> any()

Equivalent to start_register_if_not_running(node(), Name, Module, Function, Args).

start_register_if_not_running/5

start_register_if_not_running(Node::atom(), Name::atom(), Module::atom(), Function::atom(), Args::list()) -> pid() | ok

Documentary Check whether a process is registered locally, and if not, spawn it with a give function and arguments.

  1> whereis(test).
  undefined
 
  2> scutil:start_register_if_not_running(node(), test, scutil, wait_until_terminate, []).
  ok
 
  3> whereis(test).
  <0.726.0>
 
  4> test ! terminate.
  terminate
 
  5> whereis(test).
  undefined
 
  6> scutil:start_register_if_not_running(node(), test, scutil, wait_until_terminate, []).
  true
 
  7> whereis(test).
  <0.731.0>
 
  8> scutil:start_register_if_not_running(node(), test, scutil, wait_until_terminate, []).
  ok
 
  9> whereis(test).
  <0.731.0>

Introduced in: Version 8

std_deviation/1

std_deviation(Values::numericlist()) -> float()

Statistics Measures the standard deviation of the values in the list.

  1> scutil:std_deviation([1,2,3,4,5]).
  1.4142135623730951
 
  2> scutil:std_deviation([2,2,2,2,2]).
  0.0

Introduced in: Version 39

tied_ranks_of/1

tied_ranks_of(Values::numericlist()) -> rankinglist()

Statistics Returns a ranked ordering of the list with tie rankings. As such, for uniformity, all rankings are floats. Ties are represented as the centers of ranges.

  1> scutil:tied_ranks_of([10,90,20,80,30,70,40,60,50]).
  [{1.0,90}, {2.0,80}, {3.0,70}, {4.0,60}, {5.0,50}, {6.0,40}, {7.0,30}, {8.0,20}, {9.0,10}]
 
  2> scutil:tied_ranks_of([100,200,200,300]).
  [{1.0,300},{2.5,200},{2.5,200},{4.0,100}]

Introduced in: Version 42

to_lines/1

to_lines(Text::string()) -> stringlist()

String Cuts a string according to any of the three newline conventions (even mixed), and discards empty strings.

  1> scutil:to_lines("one\rtwo\nthree\r\nfour\r\r\rfive").
  ["one","two","three","four","five"]

Introduced in: Version 2

tuple_member/2

tuple_member(E::any(), T::tuple()) -> true | false

Checks whether E is a member element of tuple T, analogous to lists::member(E, L).

  1> scutil:tuple_member(b, {a,b,c}).
  true
 
  2> scutil:tuple_member(d, {a,b,c}).
  false
 
  3> scutil:tuple_member([1,2], {[1,2]}).
  true

Introduced in: Version 123

tuple_sum/1

tuple_sum(T::relaxed_numeric_tuple()) -> number()

Math Returns the sum of the numeric elements of a tuple, treating non-numeric elements as zero.

  1>

Introduced in: Version 86

type_of/1

type_of(Argument::any()) -> typelabel()

Utility Fetch the type of the argument. Valid for any term. Fails before erlang 12, due to use of is_bitstring() .

  1> scutil:type_of(1).
  integer
 
  2> scutil:type_of({hello,world}).
  tuple

Introduced in: Version 14

u32_iolist_to_int/1

u32_iolist_to_int(X1) -> any()

Equivalent to u32_iolist_to_int(A, B, C, D, little).

u32_iolist_to_int/2

u32_iolist_to_int(X1, X2) -> any()

Equivalent to u32_iolist_to_int(A, B, C, D, Endianness).

u32_iolist_to_int/4

u32_iolist_to_int(A, B, C, D) -> any()

Equivalent to u32_iolist_to_int(A, B, C, D, little).

u32_iolist_to_int/5

u32_iolist_to_int(A, B, C, D, X5) -> any()

u64_iolist_to_int/1

u64_iolist_to_int(X1) -> any()

Equivalent to u64_iolist_to_int(A, B, C, D, E, F, G, H, little).

u64_iolist_to_int/2

u64_iolist_to_int(X1, X2) -> any()

Equivalent to u64_iolist_to_int(A, B, C, D, E, F, G, H, Endianness).

u64_iolist_to_int/8

u64_iolist_to_int(A, B, C, D, E, F, G, H) -> any()

Equivalent to u64_iolist_to_int(A, B, C, D, E, F, G, H, little).

u64_iolist_to_int/9

u64_iolist_to_int(A, B, C, D, E, F, G, H, X9) -> any()

unit_scale_signal/1

unit_scale_signal(Waveform) -> any()

Introduced in: Version 129

vector_magnitude/1

vector_magnitude(VX) -> any()

Equivalent to root_sum_square(VX).

Math Returns the magnitude of a vector. A vector's magnitude is the length of its hypoteneuse (and is as such the root sum square of its components). A vector can be seen as the product of its unit vector and its magnitude; as such many people see a vector's magnitude as its scale.

  1> scutil:vector_magnitude([0,0,0]).
  0.0
 
  2> scutil:vector_magnitude([1,0,0]).
  1.0
 
  3> scutil:vector_magnitude([1,1,1]).
  1.7320508075688772
 
  4> scutil:vector_magnitude([1,2,3]).
  3.7416573867739413
 
  5> scutil:vector_magnitude([0,0.4,0.6,0.2,0.4,0.529150262213]).
  1.0000000000000433

Introduced in: Version 85

wait_until_terminate/0

wait_until_terminate() -> any()

Equivalent to wait_until_terminate(quiet).

wait_until_terminate/1

wait_until_terminate(IsQuiet::atom()) -> ok

walk_unique_pairings/2

walk_unique_pairings(R, F) -> any()

weighted_arithmetic_mean/1

weighted_arithmetic_mean(InputList::weightlist()) -> float()

Statistics Take the weighted arithmetic mean of the input values.

  1> scutil:weighted_arithmetic_mean([ {8,1}, {3,4}, {16,1} ]).
  6.0

Introduced in: Version 44

See also: amean_vector_normal/1, arithmetic_mean/1.

zip_n/1

zip_n(Ls::list()) -> list_of_tuples()

Equivalent to zip_n(Ls, to_tuple).

zip_n/2

zip_n(Ls::list(), ResultType::atom()) -> list_of_tuples()

List Computes a zip on any sized group of lists, rather than just two or three as offered by the lists module.

This is actually more efficient than one might expect at first glance. I ran a benchmark of 100,000 transformations of a list of lists into a list of tuples using benchmark/3 and multi_do/4 against both zip_n and the library function zip3; the library function won at 150 seconds to 175, which is a far smaller difference than I expected.
  1> Testy = [ [1,2,3], [1,2,3], [1,2,3] ].
  [[1,2,3],[1,2,3],[1,2,3]]
 
  2> scutil:benchmark(scutil, multi_do, [100000, scutil, zip_n, [Testy]]).
  {174.95563, [[{1,1,1},{2,2,2},{3,3,3}], [{1,1,1},{2,2,2},{3,3,3}], ... }
 
  3> scutil:benchmark(scutil, multi_do, [100000, lists, zip3, Testy]).
  {149.605, [[{1,1,1},{2,2,2},{3,3,3}], [{1,1,1},{2,2,2},{3,3,3}], ... }
Thanks Thanks to Vladimir Sessikov for contributing this to and thus allowing conscription from the mailing list.

Introduced in: Version 108


Generated by EDoc, Feb 26 2009, 21:23:13.