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.)
# 20200704 added Perl programming solution
 
package Writer;
 
use strict;
use warnings;
 
sub new {
   my ($class, $value, $log) = @_;
   return bless [ $value => $log ], $class;
}
 
sub Bind {
   my ($self, $code) = @_;
   my ($value, $log) = @$self;
   my $n = $code->($value);
   return Writer->new( @$n[0], $log.@$n[1] );
}
 
sub Unit { Writer->new($_[0], sprintf("%-17s: %.12f\n",$_[1],$_[0])) }
 
sub root { Unit sqrt($_[0]), "Took square root" }
 
sub addOne { Unit $_[0]+1, "Added one" }
 
sub half { Unit $_[0]/2, "Divided by two" }
 
print Unit(5, "Initial value")->Bind(\&root)->Bind(\&addOne)->Bind(\&half)->[1];
 