Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

More philosophy about continuation—passing style (CPS) and Monads..

3 views
Skip to first unread message

World90

unread,
May 30, 2021, 1:18:42 PM5/30/21
to
Hello,,


More philosophy about continuation—passing style (CPS) and Monads..

As mentioned in The essence of functional programming (Read here:
https://cs.uwaterloo.ca/~david/cs442/monads.pdf):

Programming with Monads strongly reminiscent of continuation—passing
style (CPS), and this paper explores the relationship between the two.
In a sense they are equivalent: CPS arises as a special case of a monad,
and any monad may be embedded in CPS by changing the answer type. But
the monadic approach provides additional insight and allows a finer
degree of control.

I think you need continuation—passing style (CPS) and other functional
patterns with OOP to be able to scale massively, so you need Monads so
that to scale massively, and with a Monad, a programmer can turn a
complicated sequence of functions into a succinct pipeline that
abstracts away auxiliary data management, control flow, or side-effects.

And here is an example of a Monad in Delphi:

--

program Maybe_monad;

{$APPTYPE CONSOLE}

uses
System.SysUtils;

type
TmList = record
Value: PInteger;
function ToString: string;
function Bind(f: TFunc<PInteger, TmList>): TmList;
end;

function _Unit(aValue: Integer): TmList; overload;
begin
Result.Value := GetMemory(sizeof(Integer));
Result.Value^ := aValue;
end;

function _Unit(aValue: PInteger): TmList; overload;
begin
Result.Value := aValue;
end;

{ TmList }

function TmList.Bind(f: TFunc<PInteger, TmList>): TmList;
begin
Result := f(self.Value);
end;

function TmList.ToString: string;
begin
if Value = nil then
Result := 'none'
else
Result := value^.ToString;
end;

function Decrement(p: PInteger): TmList;
begin
if p = nil then
exit(_Unit(nil));
Result := _Unit(p^ - 1);
end;

function Triple(p: PInteger): TmList;
begin
if p = nil then
exit(_Unit(nil));
Result := _Unit(p^ * 3);
end;

var
m1, m2: TmList;
i, a, b, c: Integer;
p: Tarray<PInteger>;

begin
a := 3;
b := 4;
c := 5;
p := [@a, @b, nil, @c];

for i := 0 to High(p) do
begin
m1 := _Unit(p[i]);
m2 := m1.Bind(Decrement).Bind(Triple);

Writeln(m1.ToString: 4, ' -> ', m2.ToString);
end;
Readln;
end.


---

And the results of the program above that implement a Monad are:

3 -> 6
4 -> 9
none -> none
5 -> 12



Thank you,
Amine Moulay Ramdane.
0 new messages