The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.

Demonstrate in your programming language the following:

 Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
 Write three simple functions: root, addOne, and half
 Derive Writer monad versions of each of these functions
 Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
class WriterMonad {
 
	/** @var mixed */
	private $value;
	/** @var string[] */
	private $logs;
 
	private function __construct($value, array $logs = []) {
		$this->value = $value;
		$this->logs = $logs;
	}
 
	public static function unit($value, string $log): WriterMonad {
		return new WriterMonad($value, ["{$log}: {$value}"]);
	}
 
	public function bind(callable $mapper): WriterMonad  {
		$mapped = $mapper($this->value);
		assert($mapped instanceof WriterMonad);
		return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
	}
 
	public function value() {
		return $this->value;
	}
 
	public function logs(): array {
		return $this->logs;
	}
}
 
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
 
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
 
$result = WriterMonad::unit(5, "Initial value")
	->bind($m($root, "square root"))
	->bind($m($addOne, "add one"))
	->bind($m($half, "half"));
 
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());