fib

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package fib computes Fibonacci numbers by tail recursion, as a state machine:

fib(n)       = fib(n, 0, 1)
fib(n, a, b) = a                    if n == 0
fib(n, a, b) = fib(n-1, b, a+b)     otherwise

The machine is the call fib(n, a, b): it holds all three arguments, and each EvCall evaluates it once. A tail call replaces the arguments, so the machine is the next call and nothing is left to return to. The holder's loop is the trampoline: it fires until the call has returned.

a and b are big integers of up to Bits bits. A big.Int holds a slice, so a machine holding one could not be compared with ==; the machine holds each number as Words 64-bit words instead, and its accessors return them as big.Int values.

Index

Constants

View Source
const (
	Words = 16         // 64-bit words in a number
	Bits  = Words * 64 // bits in a number
)

The size of the numbers the call holds.

Variables

This section is empty.

Functions

This section is empty.

Types

type Event

type Event uint8

Event is an input to Fire.

const (
	EvCall Event // evaluate fib(n, a, b) once

)

Event values.

type Machine

type Machine struct {
	// contains filtered or unexported fields
}

Machine is the call fib(n, a, b). Build it with New and change it only with Fire.

func New

func New(n int64) Machine

New returns the call fib(n, 0, 1), or one in BadInput when n is negative.

func (Machine) Args

func (m Machine) Args() (n int64, a, b *big.Int)

Args returns the arguments of the call.

func (Machine) Fire

func (m Machine) Fire(e Event) (Machine, fsm.Outcome)

Fire applies e.

func (Machine) Result

func (m Machine) Result() (*big.Int, bool)

Result returns fib(n) once the call has returned.

func (Machine) State

func (m Machine) State() State

State returns the control state.

type State

type State uint8

State is the call's control state.

const (
	Calling  State // fib(n, a, b) is being evaluated
	Returned       // it returned a
	TooLarge       // a+b would not fit in Bits bits
	BadInput       // n was negative

)

State values.

func (State) String

func (s State) String() string

Directories

Path Synopsis
cmd
fib command
Command fib prints the nth Fibonacci number.
Command fib prints the nth Fibonacci number.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL