Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/Lists.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
use function Pairs\cdr;
use function Pairs\toString;

/**
* Creates new list with given $elements
* @param mixed[] $elements elements to add
* @return callable list
*/
function l(...$elements)
{
return array_reduce(array_reverse($elements), function ($acc, $item) {
Expand All @@ -18,7 +23,7 @@ function l(...$elements)
* Applies callable function $func to list $list
* @param callable $func function
* @param callable $list list
* @return result list
* @return callable list
*/
function map(callable $func, $list)
{
Expand All @@ -36,7 +41,7 @@ function map(callable $func, $list)
* Filters list $list using callable function $func
* @param callable $func function
* @param callable $list list
* @return result list
* @return callable list
*/
function filter(callable $func, $list)
{
Expand All @@ -59,7 +64,7 @@ function filter(callable $func, $list)
* @param callable $func function
* @param callable $list list
* @param mixed $acc
* @return result
* @return mixed
*/
function reduce(callable $func, $list, $acc = null)
{
Expand All @@ -74,7 +79,7 @@ function reduce(callable $func, $list, $acc = null)
* Concatenates two lists
* @param pair $list1
* @param pair $list2
* @return new list
* @return callable new list
*/
function append($list1, $list2)
{
Expand All @@ -88,7 +93,7 @@ function append($list1, $list2)
/**
* Reverse list $list
* @param callable $list list
* @return result
* @return callable result
*/
function reverse($list)
{
Expand Down
26 changes: 26 additions & 0 deletions src/Pairs.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

namespace Pairs;

/**
* Creates a pair with two values
* @param mixed $x first value
* @param mixed $y second value
* @return callable pair
*/
function cons($x, $y)
{
return function ($method) use ($x, $y) {
Expand All @@ -16,16 +22,31 @@ function cons($x, $y)
};
}

/**
* Extracts first value from pair
* @param callalble $pair
* @return mixed
*/
function car(callable $pair)
{
return $pair("car");
}

/**
* Extracts second value from pair
* @param callalble $pair
* @return mixed
*/
function cdr(callable $pair)
{
return $pair("cdr");
}

/**
* Converts given list to string
* @param callalble $list
* @return string
*/
function toString($list)
{
if (!isPair($list)) {
Expand All @@ -43,6 +64,11 @@ function toString($list)
return "(" . implode(", ", $arr) . ")";
}

/**
* Checks whether given $pair is valid pair
* @param callable $pair
* @return boolean
*/
function isPair($pair)
{
return is_callable($pair);
Expand Down