This repository has been archived by the owner on May 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Just.php
120 lines (108 loc) · 2.74 KB
/
Just.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace PhpFp\Maybe\Constructor;
use PhpFp\Maybe\Maybe;
/**
* An OO-looking implementation of the Just constructor in PHP.
*/
class Just extends Maybe
{
/**
* The inner value for this Maybe.
* @var mixed
*/
private $value = null;
/**
* Create a new Just instance.
* Don't construct this with a null!
* @param mixed $x The value to wrap.
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* Application, derived with chain.
* @param Maybe $that The wrapped parameter.
* @return Maybe The wrapped result.
*/
public function ap(Maybe $that) : Maybe
{
return $this->chain(
function ($f) use ($that)
{
return $that->map($f);
}
);
}
/**
* Semigroup concatenation of two Maybe values.
* @param Maybe $that Inner types must match!
* @return Maybe The concatenated value.
* @todo Make friendly with primitives.
*/
public function concat(Maybe $that) : Maybe
{
if ($that instanceof Nothing)
{
return $this;
}
return new Maybe(
$this->value->concat(
$that->fork(null)
)
);
}
/**
* PHP implemenattion of Haskell Maybe's >>=.
* @param callable $f a -> Maybe b
* @return Maybe The result of the function.
*/
public function chain(callable $f) : Maybe
{
return $f($this->value);
}
/**
* Check whether two Maybe values be equal.
* @param Maybe $that Inner types should match!
* @return bool
* @todo Make this compatible with setoid inner values.
*/
public function equals(Maybe $that) : bool
{
return $that instanceof Just
&& $this->value->equals($that->fork(null));
}
/**
* Fork this Maybe, with a default for Nothing.
* @param mixed $default In case of Nothing.
* @return mixed Whatever the Maybe's inner type is.
*/
public function fork($_)
{
return $this->value;
}
/**
* Functor map, derived from chain.
* @param callable $f The mapping function.
* @return Maybe The outer structure is preserved.
*/
public function map(callable $f) : Maybe
{
return $this->chain(
function ($a) use ($f)
{
return Maybe::of($f($a));
}
);
}
/**
* Fold for the Just constructor.
* @param callable $f The folding function.
* @param mixed $x The accumulator value.
* @return mixed The $x type and $f return type.
*/
public function reduce(callable $f, $x)
{
return $f($x, $this->value);
}
}