Pseudocode Primer

CSE 382

\( \newcommand\doubleplus{+\kern-1.3ex+\kern0.8ex} \newcommand\mdoubleplus{\ensuremath{\mathbin{+\mkern-10mu+}}} \)

Pseudocode is a good way to talk about code in a generic way that does not tie you to a specific language. Therefore it is a very good way to describe algorithms.

- Joseph Hopper

A Small Pseudocode Notation Primer

This document is intended to aid you as a student in learning, understanding, and using the pseudocode notation used in the readings and assignments for the CSE 382 class.

Types

Value Types

Operators

Lists

Declaring Lists

Building Lists

Any example listed here can be used with lists of a specified type or lists of any type. The examples listed here use lists of any type to reduce verbosity.

Reducing Lists

Data Structures

Function Declarations

All function declarations follow the same pattern. They begin with the name of the function. This is separated from the set of parameters by two colons, \(::\). The parameter set is space separated. This is then followed by a right arrow representing an assertion of truth. The arrow points at the value of the function (in programmer terms, the return value).

$$\begin{align*} function\_name&:: list\rightarrow value \end{align*}$$

Examples

Keywords

Usage Examples

A function specification without a definition

This function determines the length of a list. Notice that all specifications begin with $-spec$ to differentiate the specification from the function itself. Specifications are used to declare the function's name, parameters, and its value. The types of the parameters are also included. In the example below, $b$ is of type $Integer$. The $a$ is left as an undefined type. $$\begin{align*} -spec\ len&::[a]\rightarrow \ b:::Integer \end{align*}$$

A function declaration followed by its two clauses that are the function's definition.

This function adds all the elements of a list. $$\begin{align*} -spec\ sum &::[a]\rightarrow a:::Real\\ sum &:: [a]\rightarrow 0 \text{ }when\text{ }[a]\text{ is empty;}\\ sum &:: [h\mid t]\rightarrow h+sum\text{ }t \text{ } otherwise. \end{align*}$$

A function declaration and definition that uses previously declared functions.

This function calculates the average of a list of numbers. $$\begin{align*} -spec\ average&::[a]\rightarrow a:::Real\\ average&= sum\text{ }[a]\div len\text{ }[a]. \end{align*}$$

List Comprehensions

The pseudocode below builds a list of even integers from the list of all positive integers. $$\begin{align*} [x\in[1\ 2\ 3\ldots]\ :\ x\equiv 0\pmod{2}]\\ \end{align*}$$ Here is pseudocode that produces a list of 2-tuples. No predicate is used. $$\begin{align*} [\{x\in[1\ 2\ 3 \ldots],y\in[a b c\ldots z]\}]\\ \end{align*}$$ Multiple predicates can be applied using the boolean keywords listed above.