NAME

Sub::Fp - A Clojure / Python Toolz / Lodash inspired Functional Utility Library

SYNOPSIS

This library provides numerous functional programming utility methods, as well as functional varients of native in-built methods, to allow for consistent, concise code.

SUBROUTINES/METHODS

EXPORT

incr        reduces  flatten
drop_right  drop     take_right  take
assoc       maps     decr        chain
first       end      subarray    partial
__          find     filter      some
none        uniq     bool        spread
len         to_keys  to_vals     is_array
is_hash     every    noop        identity
flow        eql

incr

Increments the supplied number by 1

incr(1)

# => 2

decr

Decrements the supplied number by 1

decr(2)

# => 1

maps

Creates an array of values by running each element in collection thru iteratee. The iteratee is invoked with three arguments: (value, index|key, collection).

maps(sub {
    my $num = shift;
    return $num + 1;
}, [1,1,1]);

# [2,2,2]

reduces

Reduces collection to a value which is the accumulated result of running each element in collection thru iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not given, the first element of collection is used as the initial value. The iteratee is invoked with four arguments: (accumulator, value, index|key, collection).

# Implicit Accumulator

reduces(sub {
    my ($sum, $num) = @_;

    return $sum + $num;
}, [1,1,1]);

# 3


# Explict Accumulator

reduces(sub {
    my ($accum, $num) = @_;
    return {
        spread($accum),
        key => $num,
    }
}, {}, [1,2,3]);

# {
#    key => 1,
#    key => 2,
#    key => 3,
# }

flatten

Flattens array a single level deep.

flatten([1,1,1, [2,2,2]]);

# [1,1,1,2,2,2];

drop

Creates a slice of array with n elements dropped from the beginning.

drop([1,2,3])

# [2,3];

drop(2, [1,2,3])

# [3]

drop(5, [1,2,3])

# []

drop(0, [1,2,3])

# [1,2,3]

drop_right

Creates a slice of array with n elements dropped from the end.

drop_right([1,2,3]);

# [1,2]

drop_right(2, [1,2,3])

# [1]

drop_right(5, [1,2,3])

# []

drop_right(0, [1,2,3])

#[1,2,3]

take

Creates a slice of array with n elements taken from the beginning.

take([1, 2, 3);

# [1]

take(2, [1, 2, 3]);

# [1, 2]

take(5, [1, 2, 3]);

# [1, 2, 3]

take(0, [1, 2, 3]);

# []

take_right

Creates a slice of array with n elements taken from the end.

take_right([1, 2, 3]);

# [3]

take_right(2, [1, 2, 3]);

# [2, 3]

take_right(5, [1, 2, 3]);

# [1, 2, 3]

take_right(0, [1, 2, 3]);

# []

first

Returns the first item in an array

first(["I", "am", "a", "string"])

# "I"

first([5,4,3,2,1])

# 5

end

Returns the end, or last item in an array

end(["I", "am", "a", "string"])

# "string"

end([5,4,3,2,1])

# 1

len

Returns the length of the collection. If an array, returns the number of items. If a hash, the number of key-val pairs. If a string, the number of chars (following built-in split)

len([1,2,3,4])

# 4

len("Hello")

# 5

len({ key => 'val', key2 => 'val'})

#2

len([])

# 0

noop

A function that does nothing (like our government), and returns undef

noop()

# undef

identity

A function that returns its first argument

identity()

# undef

identity(1)

# 1

identity([1,2,3])

# [1,2,3]

eql

Returns 0 or 1 if the two values have == equality, with convience wrapping for different types (no need to use eq vs ==). Follows internal perl rules on equality following strings vs numbers in perl.

eql([], [])

# 1

eql(1,1)

# 1


my $obj = {};

eql($obj, $obj);

# 1


eql("123", 123)

# 1  'Following perls internal rules on comparing scalars'


eql({ key => 'val' }, {key => 'val'});

# 0 'Only identity equality'

is_sub

Returns 0 or 1 if the argument is a sub ref

is_sub()

# 0

is_sub(sub {})

# 1

my $sub = sub {};
is_sub($sub)

# 1

is_array

Returns 0 or 1 if the argument is an array

is_array()

# 0

is_array([1,2,3])

# 1

is_hash

Returns 0 or 1 if the argument is a hash

is_hash()

# 0

is_hash({ key => 'val' })

# 1

is_empty

Returns 1 if the argument is 'empty', 0 if not empty. Used on strings, arrays, hashes.

is_empty()

# 1

is_empty([])

# 1

is_empty([1,2,3])

# 0

is_empty({ key => 'val' })

# 0

is_empty("I am a string")

# 0

spread

Destructures an array / hash into non-ref context. Destructures a string into an array of chars (following in-built split)

spread([1,2,3,4])

# 1,2,3,4

spread({ key => 'val' })

# key,'val'

spread("Hello")

# 'H','e','l','l','o'

bool

Returns 0 or 1 based on truthiness of argument, following internal perl rules based on ternary coercion

bool([])

# 1

bool("hello!")

# 1

bool()

# 0

bool(undef)

# 0

to_keys

Creates an array of the key names in a hash, indicies of an array, or chars in a string

to_keys([1,2,3])

# [0,1,2]

to_keys({ key => 'val', key2 => 'val2' })

# ['key', 'key2']

to_keys("Hey")

# [0, 1, 2];

to_vals

Creates an array of the values in a hash, of an array, or string.

to_vals([1,2,3])

# [0,1,2]

to_vals({ key => 'val', key2 => 'val2' })

# ['val', 'val2']

to_vals("Hey");

# ['H','e','y'];

uniq

Creates a duplicate-free version of an array, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array.

uniq([2,1,2])

# [2,1]

uniq(["Hi", "Howdy", "Hi"])

# ["Hi", "Howdy"]

assoc

Returns new hash, or array, with the updated value at index / key. Shallow updates only

assoc([1,2,3,4,5,6,7], 0, "item")

# ["item",2,3,4,5,6,7]

assoc({ name => 'sally', age => 26}, 'name', 'jimmy')

# { name => 'jimmy', age => 26}

subarray

Returns a subset of the original array, based on start index (inclusive) and end idx (not-inclusive)

subarray(["first", "second", "third", "fourth"], 0,2)

# ["first", "second"]

find

Iterates over elements of collection, returning the first element predicate returns truthy for.

my $people = [
    {
        name => 'john',
        age => 25,
    },
    {
        name => 'Sally',
        age => 25,
    }
]

find(sub {
    my $person = shift;
    return eql($person->{'name'}, 'sally')
}, $people);

# { name => 'sally', age => 25 }

# find also supports 'iteratee object shorthand'

my $people = [
    {
        name          => 'john',
        age           => 25,
        favorite_food => 'broccoli',
    },
    {
        name          => 'Sally',
        age           => 25,
        favorite_food => 'oranges',
    },
    {
        name          => 'Old Greg',
        age           => 100,
        favorite_food => 'you do not want to know,
    }
]

find({ favorite_food => 'broccoli' }, $people);

# [
#     {
#         name          => 'Sally',
#         age           => 25,
#         favorite_food => 'broccoli',
#     },
# ]

filter

Iterates over elements of collection, returning only elements the predicate returns truthy for.

my $people = [
    {
        name => 'john',
        age => 25,
    },
    {
        name => 'Sally',
        age => 25,
    },
    {
        name => 'Old Greg',
        age => 100,
    }
]

filter(sub {
    my $person = shift;
    return $person->{'age'} < 30;
}, $people);

# [
#    {
#        name => 'john',
#        age => 25,
#    },
#    {
#        name => 'Sally',
#        age => 25,
#    }
# ]

# Filter also supports 'iteratee object shorthand'

filter({ name => 'John' }, $people);

# [
#    {
#        name => 'john',
#        age  => 25,
#    },
# ]

none

If one element is found to return truthy for the given predicate, none returns 0

my $people = [
    {
        name => 'john',
        age => 25,
    },
    {
        name => 'Sally',
        age => 25,
    },
    {
        name => 'Old Greg',
        age => 100,
    }
]

none(sub {
    my $person = shift;
    return $person->{'age'} > 99;
}, $people);

# 0

none(sub {
    my $person = shift;
    return $person->{'age'} > 101;
}, $people);

# 1

# none also supports 'iteratee object shorthand'

none({ name => 'Black Bart' }, $people);

# 1

every

Itterates through each element in the collection, and checks if element makes predicate return truthy. If all elements cause predicate to return truthy, every returns 1;

every(sub {
    my $num = shift;
    $num > 0;
}, [1,2,3,4]);

# 1

every(sub {
    my $num = shift;
    $num > 2;
}, [1,2,3,4]);

# 0

# every also supports 'iteratee object shorthand'

my $people = [
    {
        name => 'john',
        age => 25,
        favorite_food => 'broccoli',
    },
    {
        name => 'Sally',
        age => 25,
        favorite_food => 'broccoli',
    },
    {
        name => 'Old Greg',
        age => 100,
        favorite_food => 'you do not want to know,
    }
]

every({ favorite_food => 'broccoli' }, $people)

# 0

some

Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy.

some(sub {
    my $num = shift;
    $num > 0;
}, [1,2,3,4]);

# 1

some(sub {
    my $num = shift;
    $num > 2;
}, [1,2,3,4]);

# 1

# some also supports 'iteratee object shorthand'

my $people = [
    {
        name => 'john',
        age => 25,
        favorite_food => 'broccoli',
    },
    {
        name => 'Sally',
        age => 25,
        favorite_food => 'broccoli',
    },
    {
        name => 'Old Greg',
        age => 100,
        favorite_food => 'you do not want to know,
    }
]

some({ favorite_food => 'broccoli' }, $people)

# 1

partial

Creates a function that invokes func with partials prepended to the arguments it receives. (funcRef, args)

my $add_three_nums = sub {
    my ($a, $b, $c) = @_;

    return $a + $b + $c;
};

my $add_two_nums = partial($add_three_nums, 1);

$add_two_nums->(1,1)

# 3


# Can also use __ to act as a placeholder

my $add_four_strings = sub {
    my ($a, $b, $c, $d) = @_;

    return $a . $b . $c . $d;
};

my $add_two_strings = partial($add_four_strings, "first ", __, "third ", __);

$add_two_strings->("second ", "third ")

# "first second third fourth"

chain

Composes functions, left to right, and invokes them, returning the result. Accepts an expression as the first argument, to be passed as the first argument to the proceding function

chain(
    [1,2,3, [4,5,6]],
    sub {
        my $array = shift;
        return [spread($array), 7]
    },
    \&flatten,
);

# [1,2,3,4,5,6,7]


# Invokes first function, and uses that as start value for next func
chain(
    sub { [1,2,3, [4,5,6]] },
    sub {
        my $array = shift;
        return [spread($array), 7]
    },
    \&flatten,
)

# [1,2,3,4,5,6,7]

flow

Creates a function that returns the result of invoking the given functions, where each successive invocation is supplied the return value of the previous.

my $addTwo = flow(\&incr, \&incr);

$addTwo->(1);

# 3

AUTHOR

Kristopher C. Paulsen, <kristopherpaulsen+cpan at gmail.com>

BUGS

Please report any bugs or feature requests to bug-sub-fp at rt.cpan.org, or through the web interface at https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sub-Fp. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc Sub::Fp

You can also look for information at:

ACKNOWLEDGEMENTS

LICENSE AND COPYRIGHT

MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.