### Basic evaluator

The paper illustrates application of monads to functional programming by means of a series of variations on a tiny example program, a module for evaluating simple expressions.The evaluator works on two types of term:

- A term is either a
**constant**, denoted by the tuple**{con, A}**where A is some integer, - Or it is a
**quotient**, denoted**{dv, T, U}**where T and U are other terms.

There are also two example expressions to test, called

**Answer**and

**Error**:

- Answer represents the calculations (1972/2)/23 = 42 (I get the allusion) and
- Error represents 1/0 so it is there to cause an error.

-module(eval0).

-export([eval/1]).

-export([answer/0, error/0]).

% Basic evaluator

eval({con, A}) ->

A;

eval({dv, T, U}) ->

eval(T) div eval(U).

answer() ->

{dv, {dv, {con, 1972}, {con, 2}}, {con, 23}}.

error() ->

{dv, {con, 1}, {con, 0}}.

So I can load this code into the Erlang shell and evaluate the two expressions answer and error:

C:\Users\polly\Erlang>erl

Eshell V5.10.2 (abort with ^G)

1> l(eval0).

{module,eval0}

2> eval0:eval(eval0:answer()).

42

3> eval0:eval(eval0:error()).

** exception error: an error occurred when evaluating an arithmetic expression

in function eval0:eval/1 (c:/Users/polly/Erlang/eval0.erl, line 10)

4> q().

ok

5>

C:\Users\polly\Erlang>

So answer brings back the answer 42, and error leads to an exception in the shell.

## No comments:

## Post a Comment