Skip to content

Latest commit

 

History

History
769 lines (666 loc) · 25.8 KB

File metadata and controls

769 lines (666 loc) · 25.8 KB

API

This contains an overview of all functions over the different packages

DEFAULT IMPORTS

All default imports are testest in t/00-core.t. This file also gives a good overview of the functionality of Sq itself.

# Compares if two values are the same or not.
equal($any1, $any2)

sq  ($any)              # Recursively adds blessing to Array/Hash Data-structure
call($method, @args)    # same as: sub($obj)   { $obj->$method(@args)        }
key ($id)               # same as: sub($hash)  { $hash->{$id}                }
key_equal($key, $value) # same as: sub($hash)  { equal($hash->{$id}, $value) }
idx($index)             # same as: sub($array) { $array->[$index]            }
assign { }              # a new block of scope
seq    { 1, 2, 3 }      # (easy) way to create a sequence of values
new($class,@args)       # special dispatch; used for testing; reserved;
                        # not really used in Sq itself. More an interesting
                        # syntax playground to think about.

# functions for type-checking
get_type ($any) -> Str   # Returns Type as String: Str, Num, Array, Hash, Sub, Regex, (or what "ref" returns)
is_num   ($any) -> $bool
is_str   ($any) -> $bool
is_array ($any) -> $bool
is_hash  ($any) -> $bool
is_seq   ($any) -> $bool
is_opt   ($any) -> $bool
is_result($any) -> $bool
is_sub   ($any) -> $bool
is_regex ($any) -> $bool
is_ref   ($any) -> $bool
is_type  ($any) -> $bool

fn($name, $sub)     # installs a sub-reference as $name in current package
multi($name, @tf)   # creates function with multi-dispatch based on type
with_dispatch(@tf)  # returns function with multi-dispatch based on type
type_cond(@tf)      # similar to with_dispatch() but the function that is
                    # returned only expects one input argument. Because of
                    # this the type don't start as an array. This makes some
                    # type definition shorter.
my $sub = dispatch($f_key, $hash)  # creates a function that uses $f_key to create a key
                                   # that is used in $hash to select a function to dispatch to
dispatch($key, Key1 => SUB, Key2 => SUB, ...) # Uses $key to select the correct dispatch.

id($any)    -> $any          # returning $any as-is
fst($array) -> $x            # $array->[0]
snd($array) -> $x            # $array->[1]
copy($any)  -> $copy_of_any  # Deep Copy of a Data-Structure

# sorting/comparision functions
by_num ()
by_str ()
by_stri()

record(@hash_keys) -> sub(@hash_values) -> $hash
lazy  ()
dump  ($any) -> void     # Dumps $any to STDERR
dumps ($any) -> $string  # Return dump($any) as string, instead of printing
static                   # See: Sq::Manual::Concepts::Statics

# Creation of data
array(@xs)  # array with blessing
hash (@kvs) # hash with blessing
Some (@xs)  # Option
None ()     # Option
Ok   ($any) # Result
Err  ($any) # Result
type        # Sq::Type
union       # Discriminated Union: See: t/16-du.t

MODULES

Sq->io

my $data = Sq->io->youtube($url)   # video information as a data-structure; needs yt-dlp installed
my $seq  = Sq->io->csv_read($file) # sequence of hashes from a CSV file

Sq->fs

Sq->fs->children      (@path)                     # all folder entries as a sequence
Sq->fs->read_text     (@path)                     # sequence of file opened as UTF-8
Sq->fs->read_text_gz  (@path)                     # opens gzip file as UTF-8 text
Sq->fs->write_text    ($file, $content)           # writes $content as $file
Sq->fs->write_text    ($file, $array_of_str)      # writes array of strings as file
Sq->fs->write_text    ($file, $seq)               # writes sequence as file
Sq->fs->write_text_gz ($file, $content)           # writes string as gziped compressed file
Sq->fs->write_text_gz ($file, $array_of_str)      # writes array of string as gziped compressed file
Sq->fs->write_text_gz ($file, $seq)               # writes sequence as gziped compressed file
Sq->fs->read_raw      ($size, @path)              # reads binary file in $size chunks
Sq->fs->compare_text  ($file1, $file2)            # checks if two files are the same
Sq->fs->read_bytes    ($size, @path)              # reads $size bytes from file
Sq->fs->make_link     ($source, $destination)     # creates relative symbolic-link from $source to $destination
Sq->fs->recurse       (@path)  -> Seq($path)      # sequence of all files recursively from directory
Sq->fs->search_upwards($entry) -> Result($path)   # checks if $entry is in current directory, otherwise goes up until root
Sq->fs->sha512        (@path)  -> Result($sha512) # return SHA512 of file

Sq->math

Sq->math->fac     ($int)
Sq->math->is_prime($number)
Sq->math->permute_count_up

Sq->fmt

Sq->fmt->table(...) # Generates a table on console
Sq->fmt->html (...) # Generates HTML from a data-structure

Sq->bench

Sq->bench->it     ($f)           # Measures execution time of $f
Sq->bench->compare($time, $subs) # Calls Benchmark::cmpthese

Sq->rand

my $seq = Sq->rand->int($min, $max)             # sequence of random integer from $min to $max
my $seq = Sq->rand->num($min, $max)             # sequence of random number from $min to $max
my $seq = Sq->rand->str($min, $max)             # sequence of random strings of length $min-$max
my $seq = Sq->rand->str($min, $max, $str_chars) # sequence of random strings of length $min-$max that uses characters from $str_chars

Sq->sys

my $path    = Sq->sys->dir            # Path::Tiny object from directory executable is in
my $env     = Sq->sys->env            # Enhanced version of %ENV. Hash blessing added and for example PATH is already split into an Array of Path::Tiny objects
my $opt_bin = Sq->sys->find_bin($exe) # Tries to find executable from PATH environtment variable
my $result  = Sq->sys->capture(@args) # Executes program. Returns Ok([$stdout,$stderr]) or Err([$exit,$stdout,$stderr])

Str

All functions are static. See Sq::Manual::Concepts::Statics for a description of what static means.

Str->chomp
Str->chop
Str->chunk
Str->collapse
Str->contains
Str->chr
Str->ends_with
Str->escape_html
Str->hex
Str->keep
Str->is_empty
Str->lc
Str->length
Str->map
Str->nospace
Str->ord
Str->remove
Str->repeat
Str->reverse
Str->split
Str->starts_with
Str->trim
Str->uc

Data Structures

Througout the API documentation i use variable names to also specify a given type you must supply. Variables that start with $f_ are functions.

$f         # a function
$f_num     # must return a number
$f_str     # must return a string
$f_map     # can return any value of any type
$f_opt     # must return an option
$f_key     # must return a key that is used as a key in a hash. So it must
           # be a string. But it should be a string that dtermines uniqueness
           # for the given element.
$predicate # A function that either returns 0 or 1
$init      # A sub-ref to initialize a value, or a value

ARRAY

# CONSTRUCTORS
Array->empty     ()
Array->one       ($x)
Array->new       (@elems)
Array->bless     ($array)
Array->from_array($array)
Array->from_hash ($hash, $f)
Array->replicate ($count, $init)
Array->init      ($count, $init)
Array->init2d    ($width, $height, $f)
Array->unfold    ($state, $f_opt)
Array->range     ($start, $stop)
Array->range_step($start, $step, $stop)

# METHODS
all              ($array, $predicate)
all_ok           ($array_of_results)
all_ok_by        ($array, $f_result)
all_some         ($array_of_options)
all_some_by      ($array, $f_opt)
any              ($array, $predicate)
as_hash          ($array)
average          ($array)
average_by       ($array, $f_map)
append           ($array1, $array2)
bind             ($array, $f_array)
cache            ($array)
cartesian        (@arrays)
concat           (@arrays)
choose           ($array, $f_opt)
chunked          ($array, $size)
chunked_size     ($array, $max_size, $f_size)
columns          ($array, $amount)
combine          ($array_of_hash, $f_key, @fields)
contains         ($array, $any)
count            ($array)
count_by         ($array, $f_key)
diff             ($arrayA, $arrayB, $f_key)
distinct         ($array)
distinct_by      ($array, $f_key)
expand           ($array)
extract          ($array, $pos, $length)
fill             ($array, $upto, $init)
find             ($array, $predicate)
find_windowed    ($array, $amount, $predicate)
first            ($array, $default=undef)
fold             ($array, $state, $folder)
fold_mut         ($array, $state, $folder)
fold_rec         ($array, $f_init, $f_state)
fsts             ($array)
group_by         ($array, $f_key)
group_fold       ($array, $f_init, $f_str, $f_state)
head             ($array)
index            ($array, $idx, $default=undef)
indexed          ($array)
intersect        ($arrayA, $arrayB, $f_key)
intersperse      ($array, $value)
is_empty         ($array)
join             ($array, $sep="")
keep             ($array, $predicate)
keep_ok          ($array_of_results)
keep_ok_by       ($array, $f_result)
keep_some        ($array_of_opt)
keep_some_by     ($array, $f_opt)
keep_type        ($array, $type)
keep_e           ($array, $expr)
keyed_by         ($array, $f_key)
last             ($array, $default=undef)
length           ($array)
map              ($array, $f_map)
map2             ($arrayA, $arrayB, $f_map)
map3             ($arrayA, $arrayB, $arrayC, $f_map)
map4             ($arrayA, $arrayB, $arrayC, $arrayD, $f_map)
mapi             ($array, $f_map)
mapn             ($array, $count, $f_map)
map_array        ($array, $f_map, $f_fold)
map_e            ($array, $expr)
map_rec          ($array, $f_map)
max              ($array, $default=undef)
max_by           ($array, $f_num)
max_str          ($array, $f_str)
max_str_by       ($array, $f_str)
mean             ($array_of_nums)
mean_by          ($array, $f_num)
min              ($array, $default=undef)
min_by           ($array, $f_num)
min_str          ($array, $default=undef)
min_str_by       ($array, $f_str)
none             ($array, $predicate)
permute          ($array)
pick             ($array, $f_opt)
reduce           ($array, $f)
remove           ($array, $predicate)
repeat           ($array, $count)
rev              ($array)
rx               ($array, $regex)
rxm              ($array, $regex)
rxs              ($array, $regex, $f)
rxsg             ($array, $regex, $f)
scan             ($array, $state, $f_state)
shuffle          ($array)
skip             ($array, $amount)
skip_while       ($array, $predicate)
slice            ($array, @idxs)
split            ($array, $regex)
snds             ($array)
sort             ($array, $comparer)
sort_by          ($array, $comparer, $f_key)
sort_hash        ($array, $comparer, $key)
sum              ($array)
sum_by           ($array, $f_map)
tail             ($array)
take             ($array, $amount)
take_while       ($array, $predicate)
to_array         ($array, $count = undef)
to_arrays        ($any)
to_array_of_array($array)
to_hash          ($array, $f_map)
to_hash_of_array ($array, $f_map)
to_seq           ($array)
trim             ($array)
windowed         ($array, $size)
zip              (@arrays)

# 2D Array
fill2d       ($aoa, $init)
map2d        ($aoa, $f)
transpose    ($aoa)
transpose_map($aoa, $f)

# Mutation
get_init($array, $idx, $init)
push    ($array, @values)
pop     ($array)
shift   ($array)
unshift ($array, @values)
blit    ($source_array, $source_index, $target_array, $target_index, $amount)

# Side-Effects
iter     ($array, $f)
itern    ($array, $amount, $f)
iter_sort($array, $comparer, $f)
iteri    ($array, $f)
iter2d   ($aoa,   $f)

HASH

# Constructors
Hash->empty     ()
Hash->new       (@args)
Hash->bless     ($hash)
Hash->locked    ($hash)
Hash->init      ($amount, $f)
Hash->from_array($array, $f)

# Methods
append      ($hashA, $hashB)
bind        ($hash, $f)
concat      (@hashes)
copy        ($hash)
diff        ($hashA, $hashB)
extract     ($hash, @keys)
find        ($hash, $predicate)
fold        ($hash, $init, $f)
fold_back   ($hash, $init, $f)
get         ($hash, $key)
has_keys    ($hash, @keys)
intersect   ($hashA, $hashB, $f)
is_empty    ($hash)
is_subset_of($hash, $other)
keep        ($hash, $predicate)
keys        ($hash)
length      ($hash)
map         ($hash, $f)
pick        ($hash, $f_opt)
remove      ($hash, $predicate)
slice       ($hash, @keys)
to_array    ($hash, $f)
to_hash     ($hash, $f)
union       ($hashA, $hashB, $f)
values      ($hash)
with        ($hash, @keys)
withf       ($hash, %kfs)
with_default($hash, %def)

# Side-Effect
iter     ($hash, $f)
iter_sort($hash, $compare, $f)
lock     ($hash, @keys)
on       ($hash, %kfs)

# Mutations
change  ($hash, %kfs)
delete  ($hash, @keys)
get_init($hash, $key, $init)
push    ($hash, $key, @values)
set     ($hash, @kvs)

Seq

# CONSTRUCTORS
Seq->empty     ()
Seq->new       (@elems)
Seq->one       ($x)
Seq->init      ($count, $init)
Seq->range     ($start, $stop)
Seq->range_step($start, $step, $stop)
Seq->concat    (@seqs)
Seq->unfold    ($state, $f_opt)
Seq->always    ($x)
Seq->up        ($start)
Seq->down      ($start)
Seq->replicate ($count, $init)
Seq->from_array($array)
Seq->from_hash ($hash)
Seq->from_sub  ($f)
Seq->stdin     ()

# METHODS
all              ($seq, $predicate)
any              ($seq, $predicate)
append           ($seq1, $seq2)
as_hash          ($seq)
average          ($seq)
average_by       ($seq,  $f_map)
bind             ($seq,  $f_seq)
cache            ($seq)
cartesian        (@seqs)
choose           ($seq, $f_opt)
chunked          ($seq, $size)
combine          ($seq, $f_key, @fields)
contains         ($seq, $any)
copy             ($seq)
count            ($seq)
count_by         ($seq, $f_key)
distinct         ($seq)
distinct_by      ($seq, $f_key)
expand           ($seq)
find             ($seq, $predicate)
find_windowed    ($seq, $amount, $predicate)
first            ($seq)
flatten          ($seq_of_seq)
fold             ($seq, $state, $folder)
fold_mut         ($seq, $state, $folder)
fsts             ($seq)
get_init         ($seq, $idx, $init)
group_by         ($seq, $f_key)
group_fold       ($seq, $f_init, $f_str, $f_state)
head             ($seq)
index            ($seq, $idx, $default=undef)
indexed          ($seq)
infinity         ($seq)
intersect        ($seqA, $seqB, $f_key)
intersperse      ($seq,  $value)
is_empty         ($seq)
join             ($seq, $sep="")
keep             ($seq, $predicate)
keyed_by         ($seq, $f_key)
last             ($seq)
length           ($seq)
map              ($seq, $f_map)
map2             ($seqA, $seqB, $f_map)
map3             ($seqA, $seqB, $seqC, $f_map)
mapi             ($seq, $f_map)
max              ($seq, $default=undef)
max_by           ($seq, $f_num)
max_str          ($seq, $f_str)
max_str_by       ($seq, $f_str)
merge            ($seq_of_array)
mean             ($seq_of_nums)
mean_by          ($seq, $f_num)
min              ($seq, $default=undef)
min_by           ($seq, $f_num)
min_str          ($seq, $default=undef)
min_str_by       ($seq, $f_str)
none             ($seq, $predicate)
permute          ($seq)
pick             ($seq, $f_opt)
reduce           ($seq, $f)
remove           ($seq, $predicate)
repeat           ($seq, $count)
rev              ($seq)
rx               ($seq, $regex)
rxm              ($seq, $regex)
rxs              ($seq, $regex, $f)
rxsg             ($seq, $regex, $f)
skip             ($seq, $amount)
skip_while       ($seq, $predicate)
slice            ($seq, @idxs)
snds             ($seq)
sort             ($seq, $comparer)
sort_by          ($seq, $comparer, $f_key)
split            ($seq_of_str, $regex)
sum              ($seq)
sum_by           ($seq, $f_map)
tail             ($seq)
take             ($seq, $amount)
take_while       ($seq, $predicate)
to_array         ($seq, $count = undef)
to_arrays        ($any)
to_array_of_array($seq)
to_hash          ($seq, $f_map)
to_hash_of_array ($seq, $f_map)
to_seq           ($seq)
trim             ($seq)
windowed         ($seq, $size)
zip              (@seqs)

# Side-Effects
do       ($seq, $f)
doi      ($seq, $f)
do_every ($seq, $count, $f)
iter     ($seq, $f)
iteri    ($seq, $f)
itern    ($seq, $amount, $f)

Option

# Constructors
my $opt = Some(1);
my $opt = Some(1,2,3);
my $opt = None();

# Methods
bind        ($opt,  $f)
bind2       ($opt,  $optA, $optB, $f)
bind3       ($opt,  $optA, $optB, $optC, $f)
bind4       ($opt,  $optA, $optB, $optC, $optD, $f)
bind_v      (@opts, $f)
check       ($opt, $predicate)
fold        ($opt, $state, $f)
fold_back   ($opt, $state, $f)
get         ($opt)
is_some     ($any)
is_none     ($any)
iter        ($opt, $f)
match       ($opt,  Some => sub {}, None => sub {})
map         ($opt,  $f)
map2        ($optA, $optB, $f)
map3        ($optA, $optB, $optC, $f)
map4        ($optA, $optB, $optC, $optD, $f)
map_v       (@opts, $f)
or          ($opt,  @defaults)
or_with     ($opt,  $f_x)
or_else     ($opt,  $default_opt)
or_else_with($opt,  $f_opt)
single      ($opt)
to_array    ($opt)
to_seq      ($opt)
validate    ($opt, $predicate)

# Module Functions
my ($bool, @values) = Option->extract(@any)

Result

# Constructors
my $res = Ok(1);
my $res = Err(1);

# Methods
fold        ($res, $state, $f_state)
get         ($res)
is_ok       ($any)
is_err      ($any)
iter        ($res, $f)
map         ($res, $f)
map2        ($resA, $resB, $f)
map3        ($resA, $resB, $resC, $f)
map4        ($resA, $resB, $resC, $resD, $f)
mapErr      ($res, $f)
match       ($res, Ok => sub {}, Err => sub {})
or          ($res, $default)
or_with     ($res, $f)
or_else     ($res, $defalut_result)
or_else_with($res, $f_result)
to_option   ($res)
to_array    ($res)
value       ($res)

Lazy

Lazy is like a normal anonymous subroutine function that evaluates it's body only once and caches it's result. You can pass a lazy wherever a normal subroutine is expected.

my $sub   = lazy { ... };

my $value = $sub->force();
my $value = $sub->();

Sq::Parser

# Running a Parser
p_run  ($parser, $str)
p_valid($parser, $str)

# Building Parsers
p_str       (@strings)            # expects one of the strings to be succesfull
p_strc      (@strings)            # like p_str but also keeps what was matches as the result
p_match     ($regex)              # matches a regex
p_matchf    ($regex, $f_xs)       # matches regex, and does transformation
p_matchf_opt($regex, $f_opt_xs)   # like p_match but expexts an option for succeess

# change result of Parser
p_map       ($f_map, @parsers)    # maps multiple parsers into a new value
p_keep      ($parser, $predicate) # decides if result of $parser should be keept
p_choose    ($parser, $f_opt)     # like p_map but expects an optional and the parsing can thus fail
p_join      ($sep, $parser)       # all result of $parser are concatenated
p_split     ($regex, $parser)     # splits result of $parser into multiple values
p_bind      ($parser, $f_parser)  # monadic bind

# Combining Parser
p_and       (@parsers)            # every parser must be sucessfull
p_or        (@parsers)            # only one must be succesfull
p_not       ($parser)             # sucessfull if $parser fails
p_maybe     (@parsers)            # all @parsers must be present, or not
p_many      (@parsers)            # matches @parsers at least one, or many times
p_many0     (@parsers)            # matches @parsers zero or many times
p_qty       ($min, $max, $parser) # matches $parser $min up to $max times
p_repeat    ($amount, $parser)    # repeats $parser $amount times
p_ignore    ($parser)             # $parser must match, but capture will be ignored

# Special
p_empty     ()                    # empty parser
p_fail      ()                    # always fails
p_return    (@values)             # parser that returns values as-is
p_delay     ($f_parser)           # useful for building recursive parsers

# This function expects a data-structure. The parser is built from the
# data-structure. Small example. Instead of:
#
#   my $abc = p_str("a", "b", "c")
#
# you can write
#
#   my $abc = parser [str => "a", "b", "c"]
#
parser($array)

Sq::Type

# Runners
t_run   ($type, @values)
t_valid ($type, @values)
t_assert($type, @values)

# Combinators
t_and  (@types)
t_or   (@types)
t_is   ($predicate)
t_not  (@types)
t_rec  ($f_type)
t_maybe($type)

# String
t_str   (@types)
t_enum  (@strings)
t_match ($regex)
t_matchf($regex, $predicate)
t_parser($parser)            # Sq::Parser
t_eq    ($str)

# Numbers
t_num     (@types)
t_int     (@types)
t_positive()          # includes 0
t_negative()          # includes 0
t_range   ($min,$max)

# Hash
t_hash     (@types)
t_with_keys(@keys)
t_keys     (%key_type)
t_as_hash  (@types)
t_key_is   (@types)   # runs type-check on the keys (string) of a hash

# Array
t_array     (@types)
t_idx       ($index, @types)
t_tuple     (@types)
t_tuplen    ($min, @types)
t_tuplev    (@types, $type)
t_even_sized()

# 2D Array
t_aoa(@types)

# Basic Types
t_any   ()
t_sub   ()
t_regex ()
t_bool  ()
t_seq   ()
t_void  ()
t_opt   (@types)
t_result($type_ok, $type_err)
t_union ($union)
t_runion($f_union)

# Multi Use
t_of    (@types)    # Array & Hash: Checks if all values are of @types
t_min   ($min)      # Num, String Length, Array Count, Hash Count
t_max   ($max)      # Num, String Length, Array Count, Hash Count
t_length($min,$max) # String, Array, Hash

# Objects
t_ref($ref,   @types)
t_isa($class, @types)
t_can(@methods)
);

Sq::Gen

Random Data Generation Tool

TODO

Sq::Reflection

Reflection for Sq functionality.

# getting or installing functions. $name must be the full name including the Package.
get_func($name)           # get function-reference by $name, or throws EXCEPTION
set_func($name, $f)       # installs/overwrites anonymous function $f as $name

# Package information
funcs_of($package)        # returns function-reference from $package
has_func($package, $name) # Checks if $package has a function $name

# Statics
set_static($name, $f)     # Installs $f as a static function with name $name
is_static($func)          # ask if $func is a static function
statics()                 # returns an array of all static functions

# Quering information
signatures()              # Returns an array of all function with added signatures

Sq::Signature

Adds type-checking to functions with the help of Sq::Type

Sq::Signature::sigs_added() # returns an array of functions added with a signature

sig ($func_name, @types)
sigt($func_name, $in_type, $out_type)

Sq::Test

The whole Testing of Sq itself is done with Sq::Type. I started using Test2 and later replaced it. The testing system itself is a lot faster compared to Test2 because of very limited functionality, and also can easily test Sq Types itself.

When I profiled Sq (by running the test-sytem) it often came out that over 90% of the time was just spent in Test2. After my own rewrite this was gone.

Consider that all functionality and over 2500+ tests are written with just this limited functionality. You very likely don't need a lot more complex testing system.

# Functions you should use 90%+ of the time
ok ($bool, $message)           # Must be a valid value
nok($bool, $message)           # Must be an invalid value
is ($got, $expected, $message) # $got must be the same as $expected. Sq::Equality equal() is used!

# Special
check    ($got, $f_expected, $message)
check_isa($any, $class, $message)
one_of   ($got, $expects, $message)

# Exception Testing
dies { ... }
like ($str, $regex, $message)

# Calling after all tests finished
done_testing()

ok() and nok() can expects three different things as valid/invalid.

numbers: it only explicitly expects 0 or 1 as boolean. It fails on returning undef, empty string
option:  An optional value that is Some() is considered valid
result:  A Result value that is Ok() is considered valid