Primitive recursive functions

This page explains what primitive recursive functions (PRFs) are, and provides working code (Python, Haskell) for constructing and evaluating them.

Mathematical definition

A primitive recursive function maps each vector of natural numbers to a natural number. In other words, a PRF \(f\) with \(n\) arguments has the type \(f : \mathbb{N}^n \rightarrow \mathbb{N}\). The set of all possible PRFs is constructed in a special way, using only these 5 building blocks:

Basic:

Inductive:

Source code

Python version: primrecfunc.py, primrecfunctest.py

Haskell version: PrimRecFunc.hs, PrimRecFuncTest.hs

PrimRecFuncTest can be run as a main program. PrimRecFunc contains data structures that you can use to build your own computations. PrimRecFunc also contains a library of useful PRFs for arithmetic, Boolean logic, and comparisons. This library of PRFs is described near the bottom of the page.


Python code

Data type: PrimRecFunc

PrimRecFunc is a class that represents a primitive recursive function. To get a PRF, use one of these subclass objects or constructors:

Examples:

Evaluation: PrimRecFunc.eval()

To evaluate a PRF f with a vector (list) of natural numbers xs, use the expression f.eval(xs), which yields a natural number.

Examples:

Extra features


Haskell code

Data type: Prf

data Prf = Z | S | I Int Int | C Prf [Prf] | R Prf Prf | Native ([Int] -> Int)

Prf is a data type representing a primitive recursive function. To get a PRF, use one of these data constructors:

Examples:

Evaluation: eval

eval :: Prf -> [Int] -> Int

To evaluate a PRF f with a vector (list) of natural numbers xs, use the expression eval f xs, which yields a natural number.

Examples:

Extra features

Notes


Library of primitive recursive functions

These included PRFs serve as excellent examples of how to implement familiar, useful functions in terms of PRFs.

Boolean functions (0 means false, 1 means true, and all other values cause unspecified behavior):

Comparison functions (each returns a Boolean value):

Arithmetic functions:

Bitwise functions:

Read the test programs for examples of the input/output values of each library function: primrecfunctest.py, PrimRecFuncTest.hs

Mathematical properties

More info



Feedback

Question? Comment? Contact me

ProjectNayuki: Like, comment, follow updates on Facebook