Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program Either;
- {$APPTYPE CONSOLE}
- uses
- SysUtils;
- const
- IsLeft = False;
- IsRight = True;
- type
- Either<TLeft,TRight> = record
- strict private
- fIsRight: Boolean;
- fLeft: TLeft;
- fRight: TRight;
- public
- constructor FromLeft(const value: TLeft);
- constructor FromRight(const value: TRight);
- property Match: Boolean read fIsRight;
- procedure CaseOf(const left: TProc<TLeft>; const right: TProc<TRight>);
- property Left: TLeft read fLeft;
- property Right: TRight read fRight;
- class operator Implicit(const value: TLeft): Either<TLeft,TRight>;
- class operator Implicit(const value: TRight): Either<TLeft,TRight>;
- end;
- { Either<TLeft, TRight> }
- constructor Either<TLeft, TRight>.FromLeft(const value: TLeft);
- begin
- fIsRight := False;
- fLeft := value;
- fRight := Default(TRight);
- end;
- constructor Either<TLeft, TRight>.FromRight(const value: TRight);
- begin
- fIsRight := True;
- fLeft := Default(TLeft);
- fRight := value;
- end;
- procedure Either<TLeft, TRight>.CaseOf(const left: TProc<TLeft>;
- const right: TProc<TRight>);
- begin
- case Match of
- IsLeft: left(fLeft);
- IsRight: right(fRight);
- end;
- end;
- class operator Either<TLeft, TRight>.Implicit(
- const value: TLeft): Either<TLeft, TRight>;
- begin
- Result := Either<TLeft,TRight>.FromLeft(value);
- end;
- class operator Either<TLeft, TRight>.Implicit(
- const value: TRight): Either<TLeft, TRight>;
- begin
- Result := Either<TLeft,TRight>.FromRight(value);
- end;
- function Divide(x, y: Integer): Either<string,Integer>;
- begin
- if y = 0 then
- Result := 'Division by zero!'
- else
- Result := x div y;
- end;
- procedure ShowError(msg: string);
- begin
- Writeln('Error: ' + msg);
- end;
- procedure Main;
- begin
- with Divide(42, 0) do
- case Match of
- IsLeft: ShowError(Left);
- IsRight: Writeln(Right);
- end;
- // or
- Divide(42, 0).CaseOf(
- ShowError,
- procedure(i: integer)
- begin
- Writeln(i);
- end);
- end;
- begin
- try
- Main;
- except
- on E: Exception do
- Writeln(E.ClassName, ': ', E.Message);
- end;
- Readln;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement