Universal Turing machine: Difference between revisions

m
m (Updated description and link for Fōrmulæ solution)
m (→‎{{header|Wren}}: Minor tidy)
 
(82 intermediate revisions by 11 users not shown)
Line 2:
One of the foundational mathematical constructs behind computer science
is the [[wp:Universal Turing machine|universal Turing Machine]].
 
 
(Alan Turing introduced the idea of such a machine in 1936–1937.)
 
Indeed one way to definitively prove that a language
Line 9 ⟶ 12:
 
;Task:
 
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Line 84 ⟶ 86:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F run_utm(halt, state, Char blank; rules_in, [Char] &tape = [Char](); =pos = 0)
V st = state
I tape.empty
Line 165 ⟶ 167:
‘E 0 0 right STOP’.split(‘ ’, group_delimiters' 1B)],
tape' &‘2 2 2 1 2 2 1 2 1 2 1 2 1 2’.split(‘ ’).map(Char)
)</langsyntaxhighlight>
 
{{out}}
Line 336 ⟶ 338:
The execution of the machine, i.e., the procedure Run, allows to define a number Max_Steps, after which the execution stops -- when, e.g., the specified machine runs infinitively. The procedure also allows to optionally output the configuration of the machine before every step.
 
<langsyntaxhighlight Adalang="ada">private with Ada.Containers.Doubly_Linked_Lists;
 
generic
Line 389 ⟶ 391:
Right: List;
end record;
end Turing;</langsyntaxhighlight>
 
===The implementation of the universal machine===
 
<langsyntaxhighlight Adalang="ada">package body Turing is
 
function List_To_String(L: List; Map: Symbol_Map) return String is
Line 490 ⟶ 492:
end Run;
 
end Turing;</langsyntaxhighlight>
 
 
===The implementation of the simple incrementer===
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Turing;
 
procedure Simple_Incrementer is
Line 521 ⟶ 523:
Run(Tape, Rules, 20, null); -- don't print the configuration during running
Put_Tape(Tape, Stop); -- print the final configuration
end Simple_Incrementer;</langsyntaxhighlight>
 
{{out}}
Line 530 ⟶ 532:
===The implementation of the busy beaver===
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Turing;
 
procedure Busy_Beaver_3 is
Line 560 ⟶ 562:
Run(Tape, Rules, 20, Put_Tape'Access); -- print configuration before each step
Put_Tape(Tape, Stop); -- and print the final configuration
end Busy_Beaver_3;</langsyntaxhighlight>
 
{{out}}
Line 591 ⟶ 593:
111111 STOP
^</pre>
=={{header|Amazing Hopper}}==
Implementation of a Universal Turing Machine:
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#proto UniversalTuringMachine(_X_)
main:
.ctrlc
stbegin=0,stEnd=0,state=0,ptr=0
tape=0,states=0,rules=0,long=0,tapeSize=0
file="turing/prg03.tm"
// load program, rules & states:
jsub(load Archive)
// RUN Universal Turing Machine program:
i=1
__TURING_RUN__:
_Universal Turing Machine ([i,1:end]get(rules))
++i,{long,i}gt? do{ i=1 }
jt(__TURING_RUN__)
println
exit(0)
.locals
printTape:
#hl{
print(tape[1:(ptr-1)],"\R",tape[ptr],"\OFF",tape[(ptr+1):end],"\n")
//sleep(0.1)
}
up(1)
clear mark
back
Universal Turing Machine(rules)
cont=1
clear mark
#hl{
if( rules[1] == state )
if( tape[ptr] == rules[2] )
tape[ptr] = rules[3]
ptr += rules[4]
if(ptr==0)
}
++tapeSize
{0,1,tape}, array(INSERT), ++ptr
#hl{
else if(ptr>tapeSize)
}
++tapeSize
{tapeSize,tape},array(RESIZE),
[tapeSize]{0},put(tape),clear mark
#hl{
endif
state = rules[5]
if(state == stEnd)
cont=0
endif
}
jsub(print Tape)
#hl{
endif
endif
}, {cont}
back
load Archive:
{","}tok sep
{file} stats file
[1,1:end],{file},!(5),load, mov(tape)
[2,1:3], !(5),load, mov(states)
[3:end,1:5], load, mov(rules)
clear mark
[1:end,4]get(rules),colMoving=0, mov(colMoving)
{"1","RIGHT",colMoving} transform, mov(colMoving)
{"-1","LEFT",colMoving} transform, mov(colMoving)
{"0","STAY",colMoving} transform, xtonum, put(rules)
clear mark
{0}reshape(tape)
size(tape),lengthTape=0,mov(lengthTape),[2]get(lengthTape),mov(tapeSize)
#hl{
stbegin=states[1,1]
stEnd=states[1,2]
ptr=states[1,3]
state=stbegin
}
data rules=0, size(rules), mov(datarules), [2]get(data rules), mov(long)
{""}tok sep
back
</syntaxhighlight>
ALternative pseudo-function UniversalTuringMachine (fast):
<pre>
Universal Turing Machine(rules)
cont=1
clear mark
[1]get(rules),{state},eq?
do{
[ptr]get(tape),[2]get(rules),eq?,
do{
[3]get(rules),[ptr]put(tape)
[4]get(rules),plus(ptr),mov(ptr)
{ptr}zero?,do{
++tapeSize
{0,1,tape}, array(INSERT), ++ptr
}
{ptr}gthan(tapeSize),do{
++tapeSize
{tapeSize,tape},array(RESIZE),
[tapeSize]{0},put(tape),clear mark
}
[5]get(rules),mov(state)
{state,stEnd},eq? do { cont=0 }
jsub(print Tape)
}
},{cont}
back
</pre>
 
Program PRG01.TM:
<pre>row 1: tape.
row 2: initial state, halt state, and initial pointer position.
row 3 to end, columns 1 to 5: rules.</pre>
<pre>
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
a,halt,5
a,0,1,RIGHT,b
a,1,1,LEFT,c
b,0,1,LEFT,a
b,1,1,RIGHT,b
c,0,1,LEFT,b
c,1,1,STAY,halt
</pre>
Program PRG02.TM:
<pre>
1,1,1,0,0
q0,qf,1
q0,1,1,RIGHT,q0
q0,0,1,STAY,qf
</pre>
Program PRG03.TM:
<pre>
0,0,0,0,0
A,H,1
A,0,1,RIGHT,B
A,1,1,LEFT,C
B,0,1,RIGHT,C
B,1,1,RIGHT,B
C,0,1,RIGHT,D
C,1,0,LEFT,E
D,0,1,LEFT,A
D,1,1,LEFT,D
E,0,1,STAY,H
E,1,0,LEFT,A
</pre>
{{out}}
<pre>
PRG01.TM:
111111000
PRG02.TM:
11110
PRG03.TM (fragment, and veeeery slow with High-level mode :( ):
1111111111111100100100100100100100100100100100100100100100100100100100100111
</pre>
 
=={{header|APL}}==
===⍺===
{{works with|Dyalog APL}}
<langsyntaxhighlight APLlang="apl">:Namespace Turing
⍝ Run Turing machine until it halts
∇r←RunTuring (rules init halts blank itape);state;rt;lt;next
Line 670 ⟶ 839:
:EndFor
:EndNamespace</langsyntaxhighlight>
{{out}}
<pre>1_SimpleIncrementer: 1111
2_ThreeStateBeaver: 111111
3_FiveStateBeaver: 10100100100100100100100100100100... (total length: 12289)</pre>
 
===⍵===
 
{{works with|Dyalog APL}}
 
<syntaxhighlight lang="lisp">
∆I ←'QA.1' '1' 'R' 'QA'
∆I,←'QA.B' '1' 'N' 'QB'
∆INCREMENTER←∆I
 
∆B ←'QA.0' '1' 'R' 'QB'
∆B,←'QA.1' '1' 'L' 'QC'
∆B,←'QB.0' '1' 'L' 'QA'
∆B,←'QB.1' '1' 'R' 'QB'
∆B,←'QC.0' '1' 'L' 'QB'
∆B,←'QC.1' '1' 'N' 'QD'
∆BEAVER←∆B
 
∇ R←RUN(F Q H T B);I;J
I←1 ⋄ T←,T
L:→(Q≡H)/E
J←⍸(Q,'.',T[I])∘≡¨F
T[I]←F[J+1]
I←I+2-'RNL'⍳F[J+2]
Q←⊃F[J+3]
T←((I<1)⍴B),T,(I>⍴T)⍴B
I←I+I=0
→L
E:R←T I
</syntaxhighlight>
 
{{out}}
<pre>
RUN ∆INCREMENTER 'QA' 'QB' '111' 'B'
1111 4
RUN ∆BEAVER 'QA' 'QD' '0' '0'
111111 4
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">; By Uberi, http://www.autohotkey.com/board/topic/58599-turing-machine/
SetBatchLines, -1
OnExit, Exit
Line 850 ⟶ 1,058:
If (A_Gui = 1)
PostMessage, 0xA1, 2
}</langsyntaxhighlight>
<b>Input:</b>
Set Section below to desired machine, then save as <scriptname>.ini in the same folder.
Line 931 ⟶ 1,139:
 
<b>Non-universality:</b> as written, the program will fail if you try to use it with a Turing machine that has more than 256 distinct states or a tape that is longer than 704 cells. (In reality, of course, the ZX81's RAM would have been exhausted some time before you reached such a Goliath.) Allowing more states would be pretty trivial, assuming you had the memory space; just use as many bytes as you need. As for supporting a longer tape, the easiest way to do it would be to comment out the <code>PRINT</code> statements (sacrificing the animation) and add a few lines to display one screenful at a time at the very end.
<langsyntaxhighlight lang="basic">1000 PRINT AT 0,0;T$
1010 LET P=1
1020 IF P>LEN T$ THEN LET T$=T$+B$
Line 948 ⟶ 1,156:
1150 GOTO 1020
1160 LET T$=B$+T$
1170 GOTO 1000</langsyntaxhighlight>
 
====The incrementer====
Works with 1k of RAM.
<langsyntaxhighlight lang="basic">10 DIM R$(2,5)
20 LET S$=CHR$ (CODE "Q"+CODE "0")
30 LET H$=CHR$ (CODE "Q"+CODE "F")
Line 958 ⟶ 1,166:
50 LET R$(2)=S$+"B1S"+H$
60 LET B$="B"
70 LET T$="111"</langsyntaxhighlight>
{{out}}
<pre>1111</pre>
Line 964 ⟶ 1,172:
====The three-state beaver====
Requires at least 2k of RAM.
<langsyntaxhighlight lang="basic"> 10 DIM R$(6,5)
20 LET R$(1)="A01RB"
30 LET R$(2)="A11LC"
Line 974 ⟶ 1,182:
90 LET S$="A"
100 LET B$="0"
110 LET H$="H"</langsyntaxhighlight>
{{out}}
<pre>111111</pre>
Line 982 ⟶ 1,190:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
Line 1,213 ⟶ 1,421:
run(t);
}
</syntaxhighlight>
</lang>
 
{{output}}
Line 1,241 ⟶ 1,449:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
Line 1,440 ⟶ 1,648:
}
 
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,486 ⟶ 1,694:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <vector>
#include <string>
Line 1,621 ⟶ 1,829:
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
'''These are the files you'll need'''<br />
Line 1,703 ⟶ 1,911:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(defn tape
"Creates a new tape with given blank character and tape contents"
Line 1,730 ⟶ 1,938:
(let [[out action new-state] (get rules [state (head tape)])]
(recur new-state (action tape out))))))))
</syntaxhighlight>
</lang>
 
=== Tests ===
 
<langsyntaxhighlight lang="clojure">
(def simple-incrementer
(new-machine {:initial :q0
Line 1,775 ⟶ 1,983:
(is (= 4098 (get freq 1)))
(is (= 8191 (get freq 0)))))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Bidirectional 'infinite' tape
tape = cluster [T: type] is make, left, right, get_cell, set_cell,
elements, get_size
rep = record[
blank: T,
loc: int,
data: array[T]
]
% Make a new tape with a given blank value and initial value
make = proc (blank: T, init: sequence[T]) returns (cvt)
data: array[T]
if sequence[T]$empty(init) then
data := array[T]$[blank]
else
data := sequence[T]$s2a(init)
end
return(rep${
blank: blank,
loc: 1,
data: data
})
end make
% Move the tape head left
left = proc (tap: cvt)
tap.loc := tap.loc - 1
if tap.loc < array[T]$low(tap.data) then
array[T]$addl(tap.data,tap.blank)
end
end left
% Move the tape head right
right = proc (tap: cvt)
tap.loc := tap.loc + 1
if tap.loc > array[T]$high(tap.data) then
array[T]$addh(tap.data,tap.blank)
end
end right
% Get the value of the current cell
get_cell = proc (tap: cvt) returns (T)
return(tap.data[tap.loc])
end get_cell
 
% Set the value of the current cell
set_cell = proc (tap: cvt, val: T)
tap.data[tap.loc] := val
end set_cell
% Retrieve all touched values, one by one, from left to right
elements = iter (tap: cvt) yields (T)
for v: T in array[T]$elements(tap.data) do
yield(v)
end
end elements
% Get the current size of the tape
get_size = proc (tap: cvt) returns (int)
return(array[T]$size(tap.data))
end get_size
end tape
 
% Turing machine state table
turing = cluster [T: type] is make, add_rule, run
where T has equal: proctype (T,T) returns (bool)
A_LEFT = 'L'
A_RIGHT = 'R'
A_STAY = 'S'
state = record[name: string, term: bool]
rule = struct[
cur_state: int,
read_sym, write_sym: T,
action: char,
next_state: int
]
rep = struct[
states: array[state],
rules: array[rule],
init_state: int
]
% Find the index of a state given its name
find_state = proc (states: array[state], name: string)
returns (int) signals (bad_state)
for i: int in array[state]$indexes(states) do
if states[i].name = name then return(i) end
end
signal bad_state
end find_state
% Make a new Turing machine given a list of states
make = proc (state_seq: sequence[string], init: string, term: sequence[string])
returns (cvt) signals (bad_state)
states: array[state] := array[state]$[]
for s: string in sequence[string]$elements(state_seq) do
array[state]$addh(states, state${name: s, term: false} )
end
init_n: int := find_state(states, init) resignal bad_state
for s: string in sequence[string]$elements(term) do
term_n: int := find_state(states, s) resignal bad_state
states[term_n].term := true
end
return(rep${states: states,
init_state: init_n,
rules: array[rule]$[]})
end make
% Add a rule to the Turing machine
add_rule = proc (tur: cvt,
in_state: string,
read_sym, write_sym: T,
action: string,
out_state: string)
signals (bad_state, bad_action)
cur_state: int := find_state(tur.states, in_state) resignal bad_state
next_state: int := find_state(tur.states, out_state) resignal bad_state
act: char
if action = "left" then act := A_LEFT
elseif action = "right" then act := A_RIGHT
elseif action = "stay" then act := A_STAY
else signal bad_action
end
array[rule]$addh(tur.rules,
rule${cur_state: cur_state,
read_sym: read_sym,
write_sym: write_sym,
action: act,
next_state: next_state})
end add_rule
% Find first matching rule
find_rule = proc (rules: array[rule], st: int, sym: T)
returns (rule) signals (no_rule)
for r: rule in array[rule]$elements(rules) do
if r.cur_state = st & r.read_sym = sym then
return(r)
end
end
signal no_rule
end find_rule
% Run the Turing machine on a given tape until it terminates
run = proc (tur: cvt, tap: tape[T]) signals (no_rule)
cur: int := tur.init_state
while ~tur.states[cur].term do
r: rule := find_rule(tur.rules, cur, tap.cell) resignal no_rule
tap.cell := r.write_sym
if r.action = A_LEFT then tape[T]$left(tap)
elseif r.action = A_RIGHT then tape[T]$right(tap)
end
cur := r.next_state
end
end run
end turing
 
 
% Simple incrementer
simple_incrementer = proc () returns (turing[char])
tc = turing[char]
t: tc := tc$make(
sequence[string]$["q0", "qf"],
"q0",
sequence[string]$["qf"]
)
tc$add_rule(t, "q0", '1', '1', "right", "q0")
tc$add_rule(t, "q0", 'B', '1', "stay", "qf")
return(t)
end simple_incrementer
 
% Three state beaver
three_state_beaver = proc () returns (turing[char])
tc = turing[char]
t: tc := tc$make(
sequence[string]$["a", "b", "c", "halt"],
"a",
sequence[string]$["halt"]
)
tc$add_rule(t, "a", '0', '1', "right", "b")
tc$add_rule(t, "a", '1', '1', "left", "c")
tc$add_rule(t, "b", '0', '1', "left", "a")
tc$add_rule(t, "b", '1', '1', "right", "b")
tc$add_rule(t, "c", '0', '1', "left", "b")
tc$add_rule(t, "c", '1', '1', "stay", "halt")
return(t)
end three_state_beaver
 
% Five state beaver
five_state_beaver = proc () returns (turing[char])
tc = turing[char]
t: tc := tc$make(
sequence[string]$["A", "B", "C", "D", "E", "H"],
"A",
sequence[string]$["H"]
)
tc$add_rule(t, "A", '0', '1', "right", "B")
tc$add_rule(t, "A", '1', '1', "left", "C")
tc$add_rule(t, "B", '0', '1', "right", "C")
tc$add_rule(t, "B", '1', '1', "right", "B")
tc$add_rule(t, "C", '0', '1', "right", "D")
tc$add_rule(t, "C", '1', '0', "left", "E")
tc$add_rule(t, "D", '0', '1', "left", "A")
tc$add_rule(t, "D", '1', '1', "left", "D")
tc$add_rule(t, "E", '0', '1', "stay", "H")
tc$add_rule(t, "E", '1', '0', "left", "A")
return(t)
end five_state_beaver
 
% Print the first 32 touched symbols on a tape
print_tape = proc (s: stream, t: tape[char])
n: int := 32
for c: char in tape[char]$elements(t) do
stream$putc(s, c)
n := n - 1
if n=0 then break end
end
if n=0 then
stream$puts(s, "... (length: " || int$unparse(t.size) || ")")
end
stream$putl(s, "")
end print_tape
 
% Run the three Turing machines and show the results
start_up = proc ()
turing_factory = proctype () returns (turing[char])
test = record[name: string, tf: turing_factory, tap: tape[char]]
stest = sequence[test]
sc = sequence[char]
tests: stest := stest$[
test${name: "Simple incrementer",
tf: simple_incrementer,
tap: tape[char]$make('B', sc$['1','1','1'])},
test${name: "Three-state busy beaver",
tf: three_state_beaver,
tap: tape[char]$make('0', sc$[])},
test${name: "Five-state probable busy beaver",
tf: five_state_beaver,
tap: tape[char]$make('0', sc$[])}]
po: stream := stream$primary_output()
for t: test in stest$elements(tests) do
stream$puts(po, t.name || ": ")
tm: turing[char] := t.tf()
turing[char]$run(tm, t.tap)
print_tape(po, t.tap)
end
end start_up</syntaxhighlight>
{{out}}
<pre>Simple incrementer: 1111
Three-state busy beaver: 111111
Five-state probable busy beaver: 10100100100100100100100100100100... (length: 12289)</pre>
 
=={{header|Common Lisp}}==
Line 1,782 ⟶ 2,253:
# <code>front</code> contains all cells before the current cell in reverse order (i.e. the first element in <code>front</code> is the direct predecessor of the current cell)
# <code>back</code> contains the current cell as its first element, followed by all successors.
<langsyntaxhighlight lang="lisp">(defun turing (initial terminal blank rules tape &optional (verbose NIL))
(labels ((combine (front back)
(if front
Line 1,816 ⟶ 2,287:
(when verbose
(show-tape front back))
(return (combine front back))))))</langsyntaxhighlight>
 
===Recursive version===
Using the same interface and general idea as the iterative version.
<langsyntaxhighlight lang="lisp">(defun turing (initial terminal blank rules tape &optional (verbose NIL))
(labels ((run (state front back)
(if (equal state terminal)
Line 1,856 ⟶ 2,327:
back)))
 
(run initial '() tape)))</langsyntaxhighlight>
 
===Usage===
<langsyntaxhighlight lang="lisp">;; Helper function for creating the rules table
(defun make-rules-table (rules-list)
(let ((rules (make-hash-table :test 'equal)))
Line 1,913 ⟶ 2,384:
(E 1 0 left A)))
'())
0 20))</langsyntaxhighlight>
 
{{Out}}
Line 1,941 ⟶ 2,412:
5-state busy beaver (first 20 cells)
10100100100100100100...</pre>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
Line 2,242 ⟶ 2,712:
print_nl();
i := i + 1;
end loop;</langsyntaxhighlight>
{{out}}
<pre>Simple incrementer: 1111
Line 2,250 ⟶ 2,720:
===Nearly Strongly Typed Version===
This is typed a little less strongly than the Ada entry. It's fast and safe.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.string, std.conv, std.array,
std.exception, std.traits, std.math, std.range;
 
Line 2,485 ⟶ 2,955:
}
M4(tm4);
}</langsyntaxhighlight>
{{out}}
<pre>Incrementer:
Line 2,542 ⟶ 3,012:
===Simple Version===
While the precedent version is Ada-like, this is more like a script.
<langsyntaxhighlight lang="d">import std.stdio, std.typecons, std.algorithm, std.string, std.array;
 
void turing(Sy, St)(in St state, Sy[int] tape, in int pos,
Line 2,559 ⟶ 3,029:
"b": [0: tuple(1, -1, "a"), 1: tuple(1, 1, "b")],
"c": [0: tuple(1, -1, "b"), 1: tuple(1, 0, "")]]);
}</langsyntaxhighlight>
{{out}}
<pre>(0)
Line 2,576 ⟶ 3,046:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">transitions(:
local :t {}
while /= ) dup:
Line 2,617 ⟶ 3,087:
else:
return paste-together tape-left head tape
paste-together tape-left head tape</langsyntaxhighlight>
 
===Simple incrementer===
 
<langsyntaxhighlight lang="dejavu">:q0 :qf [ 1 1 1 ]
)
:q0 1 1 :right :q0
:q0 :B 1 :stay :qf
!. universal-turing-machine transitions(</langsyntaxhighlight>
{{out}}
<pre>[ 1 1 1 1 ]</pre>
Line 2,631 ⟶ 3,101:
===Three-state busy beaver===
 
<langsyntaxhighlight lang="dejavu">:a :halt []
)
:a :B 1 :right :b
Line 2,639 ⟶ 3,109:
:c :B 1 :left :b
:c 1 1 :stay :halt
!. universal-turing-machine transitions(</langsyntaxhighlight>
{{out}}
<pre>[ 1 1 1 1 1 1 ]</pre>
Line 2,645 ⟶ 3,115:
===5-state, 2-symbol probable Busy Beaver machine===
 
<langsyntaxhighlight lang="dejavu">:A :H []
)
:A :B 1 :right :B
Line 2,657 ⟶ 3,127:
:E :B 1 :stay :H
:E 1 :B :left :A
!. universal-turing-machine transitions(</langsyntaxhighlight>
 
(Output omitted because of length.)
Line 2,664 ⟶ 3,134:
We define a Turing machine as an instance of TM struct, which stores the definition values (states,symbols,rules) and the current state values (state, tape, position). It can be stopped, restarted, called as a sub-program, or transformed into a sequence or stream.'Huge' TM are run in the background. Rules are compiled into a vector indexed by state * symbol.
=== Turing Machines ===
<langsyntaxhighlight lang="scheme">
(require 'struct)
 
Line 2,766 ⟶ 3,236:
(when (= final state) (writeln 'Stopping (TM-name T) 'at-pos (- pos (TM-mem T))))
count)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,820 ⟶ 3,290:
We create a task to run it in the background.
{{out}}
<langsyntaxhighlight lang="scheme">
(define steps 0)
(define (TM-task T)
Line 2,829 ⟶ 3,299:
(when (zero? count) (writeln 'END steps (date)))
(if (zero? count) #f T)) ;; return #f to signal end of task
</syntaxhighlight>
</lang>
<pre>
;; 5-states 2-symbols busy beaver
Line 2,861 ⟶ 3,331:
(for/sum ((s (TM-tape T))) s)
→ 4098
</pre>
 
=={{header|EDSAC order code}}==
This program was designed with the aim of running the 5-state busy beaver on an EDSAC simulator. It can be done, although the run time in real life would have been impossibly long (see below).
 
We know from other solutions that the Turing tape for the 5-state busy beaver requires 12289 cells. Since EDSAC memory was 1024 17-bit words, we are limited to one bit per cell, and hence to two symbols, say 0 and 1. This is enough for the Rosetta Code tasks, though not for the extra sorting task.
 
The tape is implemented as a circular buffer. Positive positions ascend from the low end of the tape area, while negative positions descend from the high end. Thus we don't need to know in advance where the zero position of the tape should be. Each EDSAC location in the tape area corresponds to 16 cells of the tape (17 would be awkward to code). If the positive and negative pointers collide, the program prints "OV" to indicate overflow.
 
When running the 5-state busy beaver, the simulator executed 2.7 billion EDSAC orders, which would have taken about 48 days on the original EDSAC. (Cf the estimate of "months" for the same task in ZX81 Basic.)
<syntaxhighlight lang="edsac">
[Attempt at Turing machine for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
 
[Library subroutine M3 prints header and is then overwritten.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*!!NR!STEPS@&#..PZ [..PZ marks end of header]
 
T48K [& (delta) parameter: Turing machine tape.]
P8F [Overwrites most of initial orders.]
 
T50K [X parameter: once-only code.]
P100F [Gets overwritten by the Turing machine tape.]
 
[Put the following as high in memory as possible,
to make room for the Turing machine tape.]
T52K [A parameter: rules and initial pattern. Also marks end]
P781F [of Turing tape, so must go immediately after tape area.]
 
T55K [V parameter: program-wide variables.]
P810F [Even address, 9 locations]
 
T46K [N parameter: constants.]
P820F [Even address]
 
T47K [M parameter: main routine.]
P859F
 
T51K [G parameter: library subroutine P7]
P988F [Even address, 35 locations.]
 
[============================= A parameter ===============================]
E25K TA GK
[0] [End of Turing tape area]
[Comment-in the desired task, or add another (2 symbols only).]
[Counts are stored in the address field.]
[Each rule is defined by an EDSAC pseudo-order, as follows:
Function letter: L = left, R = right, S = stay
Address field = new state number
Code letter: F if new symbol = 0, D if new symbol = 1.
No rule is needed for the halt state.]
[0]
[Simple incrementer: states are q0 = 0, qf = halt = 1
P1F [1 state, excluding the halt state
S1D RD [2 rules for each state (symbols 0 and 1)
P1F [1 word in tape area to be initialized
PF P3D [location 0 relative to tape, init to 7]
[3-state busy beaver: states are a = 0, b = 1, c = 2, halt = 3]
P3F [3 states, excluding the halt state]
R1D L2D [2 rules for each state (symbols 0 and 1)]
L0D R1D
L1D S3D
PF [0 words to be initialized (start with empty tape)]
[5-state busy beaver: states are A = 0, ..., E = 4, halt = 5
P5F 5 states, excluding the halt state
R1D L2D 2 rules for each state (symbols 0 and 1)
R2D R1D
R3D L4F
L0D L3D
S5D L0F
PF 0 words to be initialized (start with empty tape)]
 
[============================= X parameter ===============================]
E25K TX GK
[The following once-only code is loaded into the Turing machine tape area.]
[It runs at start-up, then gets overwritten when the tape is cleared.]
[Enter with acc = 0.]
[0] T2V [initial state assumed to be state 0]
T3V [tape head starts at position 0 on Turing tape]
T#V [reset count of steps]
T4V [initialize maximum position]
T5V [initialize minimum position]
[Calculate number of available tape positions; store in address field]
A22N [T order for exclusive end of tape]
S21N [T order for start of tape]
L4F [times 16, since each location holds 16 positions]
T25N [store for later use]
[Set up the loop in the main program that writes the initial pattern.
The main program has a list of position-value pairs.
This follows the list of rules, 2 rules per Turing machine state.]
[9] AA [number of states]
LD [times 2, because 2 rules per state]
A2F [plus 1 for the count of states]
A9@ [make A order to load number of position-value pairs]
T14@ [plant order]
[14] AM [load number of pairs (in address field)]
LD [times 2 for length of table]
TF [temp store in 0F]
A14@ [load order that was planted above]
A2F [make order to load first position]
U13M [plant in main routine]
AF [make A order for exclusive end]
T28M [plant in main routine]
[Set up order to load rules]
A26@
A2F
T18N
[Here with acc = 0. Jump to main routine.]
EM
[26] AA
 
[============================= V parameter ===============================]
E25K TV GK
[0] PFPF [number of steps (35-bit, must be at even address)]
[2] PF [current state of Turing machine]
[3] PF [current tape position, stored in address field]
[4] PF [maximum position on the tape so far]
[5] PF [minimum position on the tape so far]
[6] PF [rule for current state and symbol]
[7] PF [working group of 16 cells (1 EDSAC location)]
[8] PF [mask to select bit for current cell]
 
[============================= N parameter ===============================]
E25K TN GK
[17-bit masks: 11111111111111110, 11111111111111101, ..., 10111111111111111]
[0] V2047F V2046D V2045D V2043D V2039D V2031D V2015D V1983D
V1919D V1791D V1535D V1023D C2047D B2047D G2047D M2047D
[16] OF [add to A order to make T order with same address]
[17] AN [A order to load first mask in table]
[18] AF [A order to load first rule]
[19] A& [A order for start of tape]
[20] AA [A order for end of tape]
[21] T& [T order for start of tape]
[22] TA [T order for exclusive end of tape]
[23] P2047F [mask to pick out state from a Turing machine rule]
[24] P15F [mask to extract bit number from position]
[25] PF [number of tape positions available (calculated)]
[26] @F [carriage return]
[27] &F [line feed]
[28] K4096F [null]
[29] K2048F [set letters on teleprinter]
 
[============================= M parameter ===============================]
E25K TM GK
[Once-only code jumps to here with acc = 0]
[Clear the tape; this overwrites the once-only code]
[0] A21N [load T order for start of tape]
E3@ [always jump (since T > 0)]
[2] A22N [loop here after testing for end]
[3] T4@ [plant order to clear 1 location]
[4] TF [execute order]
A4@ [load order just executed]
A2F [inc address]
S22N [test for end]
G2@ [if not end, loop back]
[Here with acc = 0]
[Set up the starting pattern, i.e write 1's at zero or more positions on the tape.]
[To save space, the orders marked (*) are set up by the once-only code.]
[9] A13@ [load A order for next relative addess]
S28@ [compare with A order for exclusive end]
E29@ [if all done, jump out with acc = 0]
TF [clear acc]
[13] AF [(*) load relative address from table]
G17@ [jump if < 0]
A21N [make T order, addr counted from low end of tape]
E18@ [join commoon code (always jumps since T > 0)]
[17] A22N [make T order, addr counted from high end of tape]
[18] T23@ [plant T order in code]
A13@ [make order to load value from table]
A2F
T22@ [plant in code]
[22] AF [load value from table]
[23] TF [store in tape]
A22@ [make A order for next address]
A2F
T13@ [plant in code]
E9@ [always loop back]
[28] AF [(*) A order for exclusive end of list]
[29]
[Next step, i.e. set up new symbol, state and tape position.]
[Acc must be 0 here.]
[Get tape position and deduce corresponding EDSAC location and bit number.]
[29] H24N [mask for bit number]
C3V [acc := bit number]
UF [save bit number in 0F address field]
A17N [make order to load from mask table]
T44@ [plant order in code]
A3V [position]
SF [remove bit number part]
R4F [divide by 16 for relative address]
[If it's a non-negative address, add it to the start of the tape in EDSAC memory.]
[If it's a negative address, add it to the end of the tape.]
G40@ [jump if negative address]
A19N [make A order to load from tape]
G41@ [always jump to common code, since A < 0]
[40] A20N [here if negative address]
[41] U46@ [store order to load current group of 16 bits]
A16N [convert to T order at same address]
T69@ [store T order (a fair way down the code)]
[44] AF [load mask]
T8V
[46] AF [load group]
T7V
[Get rule for this state and symbol (where symbol = 0 or 1)]
H8V
C7V [acc := bit group with current bit cleared]
S7V [acc := 0 if bit is 0, -1 if bit is 1]
E54@
TF [clear acc]
A2F [to inc rule address if symbol is 1]
[54] A2V [add state twice (because each state has 2 rules)]
A2V
A18N [manufacture A order to load rule]
T58@
[58] AF [load rule]
T6V [to work space]
[Write new symbol (0 or 1) to tape. New symbol is in low bit of rule.]
HN [H register := 111...1110]
C6V
S6V [result = 0 if new symbol is 0; -1 if it's 1]
H8V [H register = mask 1...101...1 for current bit]
G67@ [jump to set the bit]
C7V [clear the bit]
E69@ [always jump (because top bit in tape store is always 0)]
[Set bit, assuming acc = -1 here (reason why it works is a bit complicated)]
[67] C7V
S8V
[69] TF [manufactured order]
[Update position of tape head, i.e. inc by 1, dec by 1, or no change.]
[Move is in top 2 bits of rule, thus]
[1x = move left, i.e. dec position (function letter can be L)]
[00 = move right, i.e. inc position (function letter can be R)]
[01 = stay, i.e. don't change position (function letter can be S)]
A6V
G83@ [left if top bit is 1]
[72] LD [else test next bit]
G95@ [skip move if next bit is 1]
[74] TF [here to move right]
A3V [inc position]
A2F
U3V
[Here we update the maximum position if latest >= maximum.]
[This is unnecessary if latest = maximum, but code is simpler this way.]
S4V [test against maximum position]
G95@ [skip if latest < maximum]
A4V [restore after test]
T4V [update maximum]
E91@ [always jump, to check for overflow]
[83] TF [here to move left]
A3V [dec position]
S2F
[86] U3V
S5V [test against current minimum position]
E95@ [jump if >= minimum]
A5V [restore acc after test]
T5V [update minimum]
[After updating maximum or minimum position, check that
available memory hasn't been exceeded.]
[91] A4V [maximum position]
S5V [subtract minimum position]
S25N [compare against number available]
E107@ [jump out if overflow]
[The next order also serves as a constant]
[95] TF [clear acc for next part]
[Increment the number of steps]
A#V
YFYF
T#V
[Finally set the new state.]
[100] H23N [mask for state bits in rule]
C6V [acc := new state]
SA [is it the last state?]
E111@ [if yes, halt the Turing machine]
AA [restore acc after test]
T2V [update state]
E29@ [loop back for next step]
[Overflow, i.e. non-negative tape positions (ascending in EDSAC memory)
collide with negative tape positions (descending).]
[107] O29N [set teleprinter to letters]
O107@ ON [print 'OV' to indicate overflow]
E116@ [jump to exit]
[Print number of steps]
[111] TF A#V [clear accc, load number of steps]
TD [number of steps to 0D for print subroutine
[114] A114 @GG [call print subroutine]
[116] O26N O27N [print CR, LF]
O28N [print null to flush teleprinter buffer]
ZF [stop]
 
[============================= G parameter ===============================]
E25K TG
[Library subroutine P7. 35 locations, even address. WWG page 18.]
[Prints non-negative integer, up to 10 digits, right-justified.]
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[========================== X parameter again ===============================]
E25K TX GK
EZ [define entry point]
PF [enter with acc = 0]
[end]
</syntaxhighlight>
{{out}}
<pre>
[Simple incrementer]
NR STEPS
4
[3-state busy beaver]
NR STEPS
13
[5-state busy beaver; requires fast EDSAC simulator]
NR STEPS
47176870
</pre>
 
Line 2,868 ⟶ 3,651:
In this universal Turing machine simulator, a machine is defined by giving it a configuration function that returns the initial state, the halting states and the blank symbol, as well as a function for the rules. These are passed in to the public interface <code>turing/3</code> as funs, together with the initial tape setup.
 
<langsyntaxhighlight lang="erlang">#!/usr/bin/env escript
 
-module(turing).
Line 2,935 ⟶ 3,718:
action(stay, _, Tape) -> Tape;
action(right, Blank, {Left, []}) -> {[Blank|Left], []};
action(right, _, {Left, [R|Rs]}) -> {[R|Left], Rs}.</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 2,967 ⟶ 3,750:
 
===Source===
This is in F77 style, and just one mainline. The Turing action is effected by just five statements:<langsyntaxhighlight Fortranlang="fortran"> 200 I = STATE*NSYMBOL - ICHAR(TAPE(HEAD)) !Index the transition.
TAPE(HEAD) = MARK(I) !Do it. Possibly not changing the symbol.
HEAD = HEAD + MOVE(I) !Possibly not moving the head.
STATE = ICHAR(NEXT(I)) !Hopefully, something has changed!
IF (STATE.GT.0) GO TO 200 !Otherwise, we might loop forever...</langsyntaxhighlight>
Which manifests the ability to read and write memory, simple arithmetic, and a conditional branch. This is all it takes. And thanks to Kurt Gödel, it is known that simple arithmetic is enough to construct statements that are true, but unprovable.
 
The use of ICHAR() and CHAR() hopefully involves no machine code effort, they are merely a genuflection to the rules of type checking to calm the compiler. Most of the blather is concerned with acquiring the description (with minimal checking), and preparing some trace output.
 
Showing the head movement with a plus sign for positive movement but not zero proved a bit tricky, given that an uninitialised MOVE entry has the obtrusive value of -60 so that function SIGN doesn't help: SIGN(1,-60) gives -1, but SIGN(1,0) gives 1. SIGN(MAX(-1,i),i) would do and now this is becoming messy, so array indexing trickery is out unless a special function is to be supplied - but this is a mainline-only attempt. The SP format code causes the appearance of a plus for subsequent fields but alas, zero has a plus sign also. So, write to a text variable, place the plus sign if wanted, and write the resulting text.<langsyntaxhighlight Fortranlang="fortran"> PROGRAM U !Reads a specification of a Turing machine, and executes it.
Careful! Reserves a symbol #0 to represent blank tape as a blank.
INTEGER MANY,FIRST,LAST !Some sizes must be decided upon.
Line 3,163 ⟶ 3,946:
END DO !On to the next symbol in the order as supplied.
END DO !And the next state, in numbers order.
END !That was fun.</langsyntaxhighlight>
 
===Results===
Line 3,728 ⟶ 4,511:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Universal_Turing_machine}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Universal Turing machine 01.png]]
In '''[https://formulae.org/?example=Universal_Turing_machine this]''' page you can see the program(s) related to this task and their results.
 
'''Test case 1. Simple incrementer'''
 
[[File:Fōrmulæ - Universal Turing machine 02.png]]
 
[[File:Fōrmulæ - Universal Turing machine 03.png]]
 
'''Test case 2. One-state busy beaver game'''
 
[[File:Fōrmulæ - Universal Turing machine 04.png]]
 
[[File:Fōrmulæ - Universal Turing machine 05.png]]
 
'''Test case 3. Two-state busy beaver game'''
 
[[File:Fōrmulæ - Universal Turing machine 06.png]]
 
[[File:Fōrmulæ - Universal Turing machine 07.png]]
 
'''Test case 4. Three-state busy beaver game'''
 
[[File:Fōrmulæ - Universal Turing machine 08.png]]
 
[[File:Fōrmulæ - Universal Turing machine 09.png]]
 
'''Test case 5. Four-state busy beaver game'''
 
[[File:Fōrmulæ - Universal Turing machine 10.png]]
 
[[File:Fōrmulæ - Universal Turing machine 11.png]]
 
'''Test case 6. (Probable) Five-state busy beaver game'''
 
In this case, the length of the tape is returned, and not the tape itself.
 
This machine will run for more than 47 millions steps.
 
[[File:Fōrmulæ - Universal Turing machine 12.png]]
 
[[File:Fōrmulæ - Universal Turing machine 13.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package turing
 
type Symbol byte
Line 3,911 ⟶ 4,734:
m.state = act.next
}
}</langsyntaxhighlight>
An example program using the above package:
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,983 ⟶ 4,806:
fmt.Println("Turing machine halts after", cnt, "operations")
fmt.Println("Resulting tape:", output)
}</langsyntaxhighlight>
{{out}}
<pre>Turing machine halts after 4 operations
Line 3,998 ⟶ 4,821:
In this program the tape is infinite, and the machines rules are coded in Haskell as a function from state and value to action, using Haskell as a DSL.
 
<langsyntaxhighlight lang="haskell">-- Some elementary types for Turing Machine
data Move = MLeft | MRight | Stay deriving (Show, Eq)
data Tape a = Tape a [a] [a]
Line 4,026 ⟶ 4,849:
runUTM rules stop start tape = steps ++ [final]
where (steps, final:_) = break ((== stop) . fst) $ iterate (step rules) (start, tape)
</syntaxhighlight>
</lang>
 
====Increment machine====
<langsyntaxhighlight lang="haskell">incr "q0" 1 = Action 1 MRight "q0"
incr "q0" 0 = Action 1 Stay "qf"
 
tape1 = tape 0 [] [1,1, 1]
machine1 = runUTM incr "qf" "q0" tape1
</syntaxhighlight>
</lang>
 
The output of the increment machine :
<langsyntaxhighlight lang="haskell">*Main> mapM_ print machine1
("q0",0000000000[1]1100000000)
("q0",0000000001[1]1000000000)
Line 4,043 ⟶ 4,866:
("q0",0000000111[0]0000000000)
("qf",0000000111[1]0000000000)
</syntaxhighlight>
</lang>
 
====Beaver machine====
<langsyntaxhighlight lang="haskell">beaver "a" 0 = Action 1 MRight "b"
beaver "a" 1 = Action 1 MLeft "c"
beaver "b" 0 = Action 1 MLeft "a"
Line 4,055 ⟶ 4,878:
tape2 = tape 0 [] []
machine2 = runUTM beaver "halt" "a" tape2
</syntaxhighlight>
</lang>
 
====Sorting test====
<langsyntaxhighlight lang="haskell">sorting "A" 1 = Action 1 MRight "A"
sorting "A" 2 = Action 3 MRight "B"
sorting "A" 0 = Action 0 MLeft "E"
Line 4,075 ⟶ 4,898:
tape3 = tape 0 [] [2,2,2,1,2,2,1,2,1,2,1,2,1,2]
machine3 = runUTM sorting "STOP" "A" tape3
</syntaxhighlight>
</lang>
 
===Using State Monad===
Line 4,081 ⟶ 4,904:
Intermediate states can be logged during execution, or they can be discarded. The initial and final states as well as errors are always logged.
Three functions are added so that machines can be written to a file and parsed/run from there. Examples are provided.
<langsyntaxhighlight lang="haskell">
import Control.Monad.State
import Data.List (intersperse, nub, find)
Line 4,234 ⟶ 5,057:
, machineLog = []
, machineLogActive = True }
</syntaxhighlight>
</lang>
Examples for machine files:
<pre>
Line 4,322 ⟶ 5,145:
This particular UTM halts when entering a final state or when a motion of 'halt' is acted on.
 
<langsyntaxhighlight lang="unicon">record TM(start,final,delta,tape,blank)
record delta(old_state, input_symbol, new_state, output_symbol, direction)
 
Line 4,439 ⟶ 5,262:
write(l,r)
write(repl(" ",*l),"^")
end</langsyntaxhighlight>
 
First sample machine, with tape changes on each transition traced:
Line 4,512 ⟶ 5,335:
===The universal (stateless point-free) Turing machine===
The universal Turing machine is defined in terms of fixed tacit (stateless point-free) code, showing that this dialect of J is Turing complete.
<langsyntaxhighlight lang="j"> ". noun define -. CRLF NB. Fixed tacit universal Turing machine code...
 
utm=.
Line 4,528 ⟶ 5,351:
 
)
</syntaxhighlight>
</lang>
 
===The incrementer machine===
<langsyntaxhighlight lang="j"> Noun=. ".@('(0 : 0)'"_)
NB. Simple Incrementer...
Line 4,551 ⟶ 5,374:
3 : ^
0 0:1111
4 : ^</langsyntaxhighlight>
 
=== The three-state busy beaver machine===
<langsyntaxhighlight lang="j"> NB. Three-state busy beaver..
NB. 0 1 Tape Symbol Scan
NB. S p m g p m g (p,m,g) → (print,move,goto)
Line 4,592 ⟶ 5,415:
12 : ^
2 1:111111
13 : ^</langsyntaxhighlight>
 
=== The probable 5-state, 2-symbol busy beaver machine===
<langsyntaxhighlight lang="j"> NB. Probable 5-state, 2-symbol busy beaver...
NB. 0 1 Tape Symbol Scan
NB. S p m g p m g (p,m,g) → (print,move,goto)
Line 4,611 ⟶ 5,434:
0 :^
4 0 :101001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001...
47176870: ^</langsyntaxhighlight>
 
=== The sorting stress test machine===
<langsyntaxhighlight lang="j"> NB. Sorting stress test...
NB. 0 1 2 3 Tape Symbol Scan
NB. S p m g p m g p m g p m g (p,m,g) ➜ (print,move,goto)
Line 4,634 ⟶ 5,457:
100: ^
4 0:0111111222222220
118: ^</langsyntaxhighlight>
 
=== The structured derivation of the universal Turing machine ===
The fixed tacit code was produced by means of an unorthodox tacit toolkit; however, the verb produced is orthodox (i.e., compliant with the language specifications):
 
<langsyntaxhighlight lang="j">NB. Structured derivation of the universal Turing machine...
 
NB.--------------------------------------------------------------------------------------
Line 4,733 ⟶ 5,556:
utm=. utm f. NB. Fixing the universal Turing machine code
 
NB. The simulation code is produced by 77 (-@:[ ]\ 5!:5@<@:]) 'utm'</langsyntaxhighlight>
 
=={{header|Java}}==
Line 4,740 ⟶ 5,563:
This is an implementation of the universal Turing machine in plain Java using standard libraries only. As generics are used, Java 5 is required. The examples (incrementer and busy beaver) are implemented directly in the main method and executed sequentially; as an additional third example, a sorting algorithm is implemented and executed in the end of the main method. During execution the complete tape and the current active transition are printed out in every step. The state names and tape symbols may contain several characters, so arbitrary strings such as "q1", "q2", ... can be valid state names or tape symbols. The machine is deterministic as the transitions are stored in a HashMap which uses state / tape symbol pairs as keys. This is self-coded, not a standard implementation, so there is no guarantee of correctness.
 
<langsyntaxhighlight Java5lang="java5">import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
Line 4,977 ⟶ 5,800:
System.out.println("Output (sort): " + machine.runTM() + "\n");
}
}</langsyntaxhighlight>
 
{{out}} -- [H] denotes the head; its position on the tape is over the symbol printed right from it.
Line 5,081 ⟶ 5,904:
=={{header|JavaScript}}==
{{works with|FireFox}}
<langsyntaxhighlight JavaScriptlang="javascript">function tm(d,s,e,i,b,t,... r) {
document.write(d, '<br>')
if (i<0||i>=t.length) return
Line 5,124 ⟶ 5,947:
'3.0: 1, L, 3',
'3.1: 1, L, 1'
)</langsyntaxhighlight>
{{out}}
Unary incrementer<br>&nbsp;&nbsp;*: a [<u>1</u>11]<br>&nbsp;&nbsp;1: a [<u>&nbsp;</u>111]<br>&nbsp;&nbsp;2: h [<u>1</u>111]<br> <br>Unary adder<br>&nbsp;&nbsp; *: 1 [<u>1</u>11&nbsp;111]<br> &nbsp;&nbsp;1: 2 [&nbsp;<u>1</u>1&nbsp;111]<br> &nbsp;&nbsp;2: 3 [&nbsp;1<u>1</u>&nbsp;111]<br> &nbsp;&nbsp;3: 3 [&nbsp;11<u>&nbsp;</u>111]<br> &nbsp;&nbsp;4: 0 [&nbsp;11<u>1</u>111]<br> <br>Three-state busy beaver<br>&nbsp;&nbsp; *: 1 [<u>&nbsp;</u>]<br> &nbsp;&nbsp;1: 2 [1<u>&nbsp;</u>]<br> &nbsp;&nbsp;2: 3 [1&nbsp;<u>&nbsp;</u>]<br> &nbsp;&nbsp;3: 3 [1<u>&nbsp;</u>1]<br> &nbsp;&nbsp;4: 3 [<u>1</u>11]<br> &nbsp;&nbsp;5: 1 [<u>&nbsp;</u>111]<br> &nbsp;&nbsp;6: 2 [1<u>1</u>11]<br> &nbsp;&nbsp;7: 2 [11<u>1</u>1]<br> &nbsp;&nbsp;8: 2 [111<u>1</u>]<br> &nbsp;&nbsp;9: 2 [1111<u>&nbsp;</u>]<br> &nbsp;10: 3 [1111&nbsp;<u>&nbsp;</u>]<br> &nbsp;11: 3 [1111<u>&nbsp;</u>1]<br> &nbsp;12: 3 [111<u>1</u>11]<br> &nbsp;13: 1 [11<u>1</u>111]<br> &nbsp;14: 0 [111<u>1</u>11]
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">import Base.show
 
@enum Move Left=1 Stay Right
Line 5,214 ⟶ 6,037:
turing(prog, tape, verbose)
end
</langsyntaxhighlight>{{out}}
<pre>
Simple incrementer
Line 5,251 ⟶ 6,074:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.2.10
 
enum class Dir { LEFT, RIGHT, STAY }
Line 5,422 ⟶ 6,245:
)
).run()
}</langsyntaxhighlight>
 
{{out}}
Line 5,474 ⟶ 6,297:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{require lib_H} // associative arrays library
 
Line 5,605 ⟶ 6,428:
output: busy_beaver2: [] -> [1,1,1,1,1,1,1,1,1,1,1]
 
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Machine definitions
local incrementer = {
name = "Simple incrementer",
Line 5,691 ⟶ 6,514:
UTM(incrementer, {"1", "1", "1"})
UTM(threeStateBB, {})
UTM(fiveStateBB, {}, "countOnly")</langsyntaxhighlight>
{{out}}
<pre>
Line 5,733 ⟶ 6,556:
Steps taken: 47176870</pre>
 
=={{header|MathematicaM2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">
===The universal machine===
Module CheckIt {
print "Universal Turing Machine"
print "------------------------"
class Machine {
private:
Head=1, Symbols=(,), States=(,)
Initial_State$, Terminating_state$, Blank_Symbol$
BS=0, Rules=list, caption$
tp$="{0:4} {1} {2} {3:5} {4:4}"
public:
Module States {
.States<=array([])
}
Module Symbols {
.Symbols<=array([])
}
Module Reset (.Initial_State$, .Terminating_state$, .Blank_Symbol$) {
if len(.States)=0 then error "No States defined"
if len(.Symbols)=0 then error "No Symbols defined"
if .States#nothave(.Initial_State$) then error "Initial State Not Exist"
if .States#nothave(.Terminating_state$) then error "Terminating State Not Exist"
it=.Symbols#pos(.Blank_Symbol$) : if it=-1 then error "Blank symbol not exist"
.BS<=it
.Rules<=List
}
Module Init (.caption$) {
flush // empty stack
print .caption$
}
Module AddRule (state$, read_symbol$, write_symbol$, action$, end_state$) {
if .States#nothave(state$) then Error "State not exist"
if .symbols#nothave(read_symbol$) then Error "Read Symbol not exist"
if .symbols#nothave(write_symbol$) then Error "Read Symbol not exist"
if ("right","left","stay")#nothave(action$) then Error "Action not exist"
if .States#nothave(end_state$) then Error "End state not exist"
try ok {
tuple=(.symbols#pos(write_symbol$), action$, end_state$)
Append .rules, state$+"_"+read_symbol$:=tuple
}
if not ok then error "rule "+ state$+"_"+read_symbol$+" already exist "
Pen 11 {
Print format$(.tp$, state$, read_symbol$, write_symbol$, action$, end_state$)
}
if stack.size>=5 then loop
}
Module Tape {
s=[]
m=each(s)
while m
it= .Symbols#pos(stackitem$(m))
if it=-1 then error "Tape symbol not exist at position ";m^
data it
end while
}
Module Run (steps as long, display as boolean) {
if len(.rules)=0 then error "No rules found"
if .Initial_State$="" or .Terminating_state$="" or .Blank_Symbol$="" then
error "Reset the machine please"
end if
if empty then push .BS
curState$=.Initial_State$
cont=true
.head<=1
dim inst$() : link inst$() to inst()
while curState$<>.Terminating_state$
if display then pen 15 {showstack()}
steps--
theRule$=curState$+"_"+.symbols#val$(stackitem(.head))
if not exist(.Rules, theRule$) then error "Undefined "+theRule$
inst$()=.Rules(theRule$)
shift .head : drop :push inst(0): shiftback .head
select case inst$(1)
case "right"
.head++ : if .head>stack.size then data .BS
case "left"
if .head<=1 then push .BS else .head--
else case
cont=false
end select
// change state
curState$=inst$(2)
// Show Stack
if steps=0 or not cont then exit
end while
if steps=0 then print over
Pen 12 {showstack()}
print "tape length: ";stack.size : flush
Refresh
sub showstack()
local d$=format$("{0:-5} {1::-5} ", curState$, .head)
local i: for i=1 to min.data(stack.size, 60): d$+=.symbols#val$(stackitem(i)):Next
print d$
end sub
}
}
Turing1=Machine()
For Turing1 {
.init "Simple incrementer"
.States "q0", "qf"
.Symbols "B", "1"
.Reset "q0", "qf", "B" // initial state, terminating state, blank symbol
.AddRule "q0", "1", "1", "right", "q0"
.AddRule "q0", "B", "1", "stay", "qf"
.tape "1", "1", "1"
.Run 100, true
}
Turing2=Machine()
For Turing2 {
.init "Three-state busy beaver"
.States "a", "b", "c", "halt"
.Symbols "0", "1"
.Reset "a", "halt", "0"
.AddRule "a", "0", "1", "right", "b", "a", "1", "1", "left", "c"
.AddRule "b", "0", "1", "left", "a", "b", "1", "1", "right", "b"
.AddRule "c", "0", "1", "left", "b", "c", "1", "1", "stay", "halt"
.Run 1000, true
}
For Turing1 {
.init "Sorter"
.States "A","B","C","D","E","X"
.Symbols "a","b","B","*"
.Reset "A", "X", "*"
.AddRule "A", "a", "a", "right", "A", "A", "b", "B", "right", "B"
.AddRule "A", "*", "*", "left", "E", "B", "a", "a", "right", "B"
.AddRule "B", "b", "b", "right", "B", "B", "*", "*", "left", "C"
.AddRule "C", "a", "b", "left", "D", "C", "b", "b", "left", "C"
.AddRule "C", "B", "b", "left", "E", "D", "a", "a", "left", "D"
.AddRule "D", "b", "b", "left", "D", "D", "B", "a", "right", "A"
.AddRule "E", "a", "a", "left", "E", "E", "*", "*", "right", "X"
.tape "b", "a", "b","b","b","a","a"
.Run 100, false
}
Turing1.tape "b","b","b","a","b","a","b","a","a","a","b","b","a"
Turing1.Run 1000, false
Turing3=Machine()
for Turing3 {
.init "5-state, 2-symbol probable Busy Beaver machine from Wikipedia"
.States "A","B","C","D", "E", "H"
.Symbols "0", "1"
.Reset "A", "H", "0"
.AddRule "A", "0", "1", "right", "B", "A", "1", "1", "left", "C"
.AddRule "B", "0", "1", "right", "C", "B", "1", "1", "right", "B"
.AddRule "C", "0", "1", "right", "D", "C", "1", "1", "left", "E"
.AddRule "D", "0", "1", "left", "A", "D", "1", "1", "left", "D"
.AddRule "E", "0", "1", "stay", "H", "E", "1", "0", "left", "A"
profiler
.Run 470, false //000000, false
Print round(timecount/1000,2);"s" // estimated 12.5 hours for 47000000 steps
}
}
CheckIt
</syntaxhighlight>
{{out}}
<pre>
(CUT VERSION)
Universal Turing Machine
------------------------
Simple incrementer
q0 1 111
q0 2 111
q0 3 111
q0 4 111B
qf 4 1111
tape length: 4
 
 
Three-state busy beaver
a 1 0
b 2 10
a 1 11
c 1 011
b 1 0111
a 1 01111
b 2 11111
b 3 11111
b 4 11111
b 5 11111
b 6 111110
a 5 111111
c 4 111111
halt 4 111111
tape length: 6
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
===The universal machine===
Updated to use dynamic definition of a function. Values computed for each input are saved.
Functionally equivalent to computing a matrix for a set of inputs.
<syntaxhighlight lang="mathematica">
 
<lang Mathematica>
left = 1; right = -1; stay = 0;
cmp[s_] := ToExpression[StringSplit[s, ","]];
Line 5,758 ⟶ 6,768:
]; {tape, rh}
];
]; </langsyntaxhighlight>
 
===A print routine and test drivers===
 
<syntaxhighlight lang="mathematica">
<lang Mathematica>
printMachine[tape_,pos_]:=(mach=IntegerString[tape,2];
ptr=StringReplace[mach,{"0"-> " ","1"->" "}];
Line 5,781 ⟶ 6,791:
fin=utm[Map[cmp,busyBeaver3S],0,0];
printMachine[fin[[1]],fin[[2]]];
</syntaxhighlight>
</lang>
 
Summary output from the 2 short machines
Line 5,794 ⟶ 6,804:
Runs in 4 minutes on an i5 desktop (with the dynamic function definiton).
The resulting tape is very long, we'll print the result of treating the value as a binary encoded integer.
<syntaxhighlight lang="mathematica">
<lang Mathematica>
probable5S={
"A, 0, 1, right, B",
Line 5,808 ⟶ 6,818:
fin=utm[Map[cmp,probable5S],0,0];
]
 
 
fin[[1]]//N
3.254757786465838*10^3698</syntaxhighlight>
</lang>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function tape=turing(rules,tape,initial,terminal)
%"rules" is cell array of cell arrays of the following form:
%First element is number representing initial state
Line 5,863 ⟶ 6,871:
end
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 5,914 ⟶ 6,922:
===The universal machine===
Source for this example was lightly adapted from [https://bitbucket.org/ttmrichter/turing https://bitbucket.org/ttmrichter/turing]. Of particular interest in this implementation is that because of the type parameterisation of the <code>config</code> type, the machine being simulated cannot be compiled if there is any mistake in the states, symbols and actions. Also, because of Mercury's determinism detection and enforcement, it's impossible to pass in a non-deterministic set of rules. At most one answer can come back from the rules interface.
<langsyntaxhighlight lang="mercury">:- module turing.
 
:- interface.
Line 5,971 ⟶ 6,979:
action(stay, _, Tape) = Tape.
action(right, Blank, (Left-[])) = ([Blank|Left]-[]).
action(right, _, (Left-[Right|Rights])) = ([Right|Left]-Rights).</langsyntaxhighlight>
 
===The incrementer machine===
This machine has been stripped of the Mercury ceremony around modules, imports, etc.
<langsyntaxhighlight lang="mercury">:- type incrementer_states ---> a ; halt.
:- type incrementer_symbols ---> b ; '1'.
 
Line 5,991 ⟶ 6,999:
incrementer(a, b, '1', stay, halt).
 
TapeOut = turing(incrementer_config, incrementer, [1, 1, 1]).</langsyntaxhighlight>
This will, on execution, fill TapeOut with [1, 1, 1, 1].
===The busy beaver machine===
This machine has been stripped of the Mercury ceremony around modules, imports, etc.
<langsyntaxhighlight lang="mercury">:- type busy_beaver_states ---> a ; b ; c ; halt.
:- type busy_beaver_symbols ---> '0' ; '1'.
 
Line 6,015 ⟶ 7,023:
busy_beaver(c, '1', '1', stay, halt).
 
TapeOut = turing(busy_beaver_config, busy_beaver, []).</langsyntaxhighlight>
This will, on execution, fill TapeOut with [1, 1, 1, 1, 1, 1].
 
Line 6,025 ⟶ 7,033:
This page also has other information, screen shots, etc.
 
<langsyntaxhighlight lang="netlogo">
;; "A Turing Turtle": a Turing Machine implemented in NetLogo
;; by Dan Dewey 1/16/2016
Line 6,399 ⟶ 7,407:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils, tables
 
proc runUTM(state, halt, blank: string, tape: seq[string] = @[],
Line 6,477 ⟶ 7,485:
"D 3 1 right A".splitWhitespace,
"E 1 1 left E".splitWhitespace,
"E 0 0 right STOP".splitWhitespace])</langsyntaxhighlight>
 
{{out}}
Line 7,231 ⟶ 8,239:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 7,313 ⟶ 8,321:
[qw/D 3 1 right A/],
[qw/E 1 1 left E/],
[qw/E 0 0 right STOP/]];</langsyntaxhighlight>
 
=={{header|Phix}}==
{{trans|Lua}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum name, initState, endState, blank, rules
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">enum</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">initState</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">endState</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">blank</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rules</span>
-- Machine definitions
constant incrementer = {
<span style="color: #000080;font-style:italic;">-- Machine definitions</span>
/*name =*/ "Simple incrementer",
<span style="color: #008080;">constant</span> <span style="color: #000000;">incrementer</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
/*initState =*/ "q0",
<span style="color: #000080;font-style:italic;">/*name =*/</span> <span style="color: #008000;">"Simple incrementer"</span><span style="color: #0000FF;">,</span>
/*endState =*/ "qf",
<span style="color: #000080;font-style:italic;">/*initState =*/</span> <span style="color: #008000;">"q0"</span><span style="color: #0000FF;">,</span>
/*blank =*/ "B",
<span style="color: #000080;font-style:italic;">/*endState =*/</span> <span style="color: #008000;">"qf"</span><span style="color: #0000FF;">,</span>
/*rules =*/ {
<span style="color: #000080;font-style:italic;">/*blank =*/</span> <span style="color: #008000;">"B"</span><span style="color: #0000FF;">,</span>
{"q0", "1", "1", "right", "q0"},
<span style="color: #000080;font-style:italic;">/*rules =*/</span> <span style="color: #0000FF;">{</span>
{"q0", "B", "1", "stay", "qf"}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"q0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"q0"</span><span style="color: #0000FF;">},</span>
}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"q0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"B"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"stay"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"qf"</span><span style="color: #0000FF;">}</span>
}
<span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">}</span>
constant threeStateBB = {
/*name =*/ "Three-state busy beaver",
<span style="color: #008080;">constant</span> <span style="color: #000000;">threeStateBB</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
/*initState =*/ "a",
<span style="color: #000080;font-style:italic;">/*name =*/</span> <span style="color: #008000;">"Three-state busy beaver"</span><span style="color: #0000FF;">,</span>
/*endState =*/ "halt",
<span style="color: #000080;font-style:italic;">/*initState =*/</span> <span style="color: #008000;">"a"</span><span style="color: #0000FF;">,</span>
/*blank =*/ "0",
<span style="color: #000080;font-style:italic;">/*endState =*/</span> <span style="color: #008000;">"halt"</span><span style="color: #0000FF;">,</span>
/*rules =*/ {
<span style="color: #000080;font-style:italic;">/*blank =*/</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span>
{"a", "0", "1", "right", "b"},
<span style="color: #000080;font-style:italic;">/*rules =*/</span> <span style="color: #0000FF;">{</span>
{"a", "1", "1", "left", "c"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"b"</span><span style="color: #0000FF;">},</span>
{"b", "0", "1", "left", "a"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"a"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"c"</span><span style="color: #0000FF;">},</span>
{"b", "1", "1", "right", "b"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"b"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"a"</span><span style="color: #0000FF;">},</span>
{"c", "0", "1", "left", "b"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"b"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"b"</span><span style="color: #0000FF;">},</span>
{"c", "1", "1", "stay", "halt"}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"c"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"b"</span><span style="color: #0000FF;">},</span>
}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"c"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"stay"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"halt"</span><span style="color: #0000FF;">}</span>
}
<span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">}</span>
constant fiveStateBB = {
/*name =*/ "Five-state busy beaver",
<span style="color: #008080;">constant</span> <span style="color: #000000;">fiveStateBB</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
/*initState =*/ "A",
<span style="color: #000080;font-style:italic;">/*name =*/</span> <span style="color: #008000;">"Five-state busy beaver"</span><span style="color: #0000FF;">,</span>
/*endState =*/ "H",
<span style="color: #000080;font-style:italic;">/*initState =*/</span> <span style="color: #008000;">"A"</span><span style="color: #0000FF;">,</span>
/*blank =*/ "0",
<span style="color: #000080;font-style:italic;">/*endState =*/</span> <span style="color: #008000;">"H"</span><span style="color: #0000FF;">,</span>
/*rules =*/ {
<span style="color: #000080;font-style:italic;">/*blank =*/</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span>
{"A", "0", "1", "right", "B"},
<span style="color: #000080;font-style:italic;">/*rules =*/</span> <span style="color: #0000FF;">{</span>
{"A", "1", "1", "left", "C"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"B"</span><span style="color: #0000FF;">},</span>
{"B", "0", "1", "right", "C"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"A"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"C"</span><span style="color: #0000FF;">},</span>
{"B", "1", "1", "right", "B"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"B"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"C"</span><span style="color: #0000FF;">},</span>
{"C", "0", "1", "right", "D"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"B"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"B"</span><span style="color: #0000FF;">},</span>
{"C", "1", "0", "left", "E"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"C"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"right"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"D"</span><span style="color: #0000FF;">},</span>
{"D", "0", "1", "left", "A"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"C"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"E"</span><span style="color: #0000FF;">},</span>
{"D", "1", "1", "left", "D"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"D"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"A"</span><span style="color: #0000FF;">},</span>
{"E", "0", "1", "stay", "H"},
<span style="color: #0000FF;">{</span><span style="color: #008000;">"D"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"D"</span><span style="color: #0000FF;">},</span>
{"E", "1", "0", "left", "A"}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"E"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"stay"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"H"</span><span style="color: #0000FF;">},</span>
}
<span style="color: #0000FF;">{</span><span style="color: #008000;">"E"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"0"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"left"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"A"</span><span style="color: #0000FF;">}</span>
}
<span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">}</span>
procedure show(string state, integer headpos, sequence tape)
printf(1," %-6s | ",{state})
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">state</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">headpos</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">tape</span><span style="color: #0000FF;">)</span>
for p=1 to length(tape) do
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %-6s | "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">state</span><span style="color: #0000FF;">})</span>
printf(1,iff(p=headpos?"[%s]":" %s "),{tape[p]})
<span style="color: #008080;">for</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tape</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">=</span><span style="color: #000000;">headpos</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"[%s]"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">" %s "</span><span style="color: #0000FF;">),{</span><span style="color: #000000;">tape</span><span style="color: #0000FF;">[</span><span style="color: #000000;">p</span><span style="color: #0000FF;">]})</span>
printf(1,"\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
-- a universal turing machine
procedure UTM(sequence machine, sequence tape, integer countOnly=0)
<span style="color: #000080;font-style:italic;">-- a universal turing machine</span>
string state = machine[initState]
<span style="color: #008080;">procedure</span> <span style="color: #000000;">UTM</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">machine</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">tape</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">countOnly</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
integer headpos = 1, counter = 0
<span style="color: #004080;">string</span> <span style="color: #000000;">state</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">initState</span><span style="color: #0000FF;">]</span>
printf(1,"\n\n%s\n%s\n",{machine[name],repeat('=',length(machine[name]))})
<span style="color: #004080;">integer</span> <span style="color: #000000;">headpos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">counter</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if not countOnly then printf(1," State | Tape [head]\n---------------------\n") end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n\n%s\n%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">name</span><span style="color: #0000FF;">],</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'='</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">name</span><span style="color: #0000FF;">]))})</span>
while 1 do
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">countOnly</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" State | Tape [head]\n---------------------\n"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if headpos>length(tape) then
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
tape = append(tape,machine[blank])
<span style="color: #008080;">if</span> <span style="color: #000000;">headpos</span><span style="color: #0000FF;">></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tape</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
elsif headpos<1 then
<span style="color: #000000;">tape</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tape</span><span style="color: #0000FF;">,</span><span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">blank</span><span style="color: #0000FF;">])</span>
tape = prepend(tape,machine[blank])
<span style="color: #008080;">elsif</span> <span style="color: #000000;">headpos</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
headpos = 1
<span style="color: #000000;">tape</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tape</span><span style="color: #0000FF;">,</span><span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">blank</span><span style="color: #0000FF;">])</span>
end if
<span style="color: #000000;">headpos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if not countOnly then show(state, headpos, tape) end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
for i=1 to length(machine[rules]) do
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">countOnly</span> <span style="color: #008080;">then</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #000000;">state</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">headpos</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">tape</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
sequence rule = machine[rules][i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rules</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
if rule[1]=state and rule[2]=tape[headpos] then
<span style="color: #004080;">sequence</span> <span style="color: #000000;">rule</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rules</span><span style="color: #0000FF;">][</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
tape[headpos] = rule[3]
<span style="color: #008080;">if</span> <span style="color: #000000;">rule</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">state</span> <span style="color: #008080;">and</span> <span style="color: #000000;">rule</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">tape</span><span style="color: #0000FF;">[</span><span style="color: #000000;">headpos</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
if rule[4] == "left" then headpos -= 1 end if
<span style="color: #000000;">tape</span><span style="color: #0000FF;">[</span><span style="color: #000000;">headpos</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rule</span><span style="color: #0000FF;">[</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span>
if rule[4] == "right" then headpos += 1 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">rule</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">==</span> <span style="color: #008000;">"left"</span> <span style="color: #008080;">then</span> <span style="color: #000000;">headpos</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
state = rule[5]
<span style="color: #008080;">if</span> <span style="color: #000000;">rule</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">==</span> <span style="color: #008000;">"right"</span> <span style="color: #008080;">then</span> <span style="color: #000000;">headpos</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
exit
<span style="color: #000000;">state</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rule</span><span style="color: #0000FF;">[</span><span style="color: #000000;">5</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #008080;">exit</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
counter += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if state=machine[endState] then exit end if
<span style="color: #000000;">counter</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while
<span style="color: #008080;">if</span> <span style="color: #000000;">state</span><span style="color: #0000FF;">=</span><span style="color: #000000;">machine</span><span style="color: #0000FF;">[</span><span style="color: #000000;">endState</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if countOnly then
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
printf(1,"Steps taken: %d\n",{counter})
<span style="color: #008080;">if</span> <span style="color: #000000;">countOnly</span> <span style="color: #008080;">then</span>
else
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Steps taken: %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">counter</span><span style="color: #0000FF;">})</span>
show(state, headPos, tape)
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #000000;">state</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">headpos</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">tape</span><span style="color: #0000FF;">)</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
UTM(incrementer, {"1", "1", "1"})
UTM(threeStateBB, {})
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
UTM(fiveStateBB, {}, countOnly:=1)</lang>
<span style="color: #000000;">UTM</span><span style="color: #0000FF;">(</span><span style="color: #000000;">incrementer</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"1"</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">UTM</span><span style="color: #0000FF;">(</span><span style="color: #000000;">threeStateBB</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{})</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- 1min 7s</span>
<span style="color: #000000;">UTM</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fiveStateBB</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{},</span> <span style="color: #000000;">countOnly</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 7,446 ⟶ 8,461:
======================
Steps taken: 47176870
"13.3s"
</pre>
Obviously the first two are near-instant but as shown the last one is a bit too much to bother with running in a browser.
 
=={{header|PHL}}==
 
<langsyntaxhighlight lang="phl">module turing;
 
extern printf;
Line 7,601 ⟶ 8,618:
emulateTuring(rules, 0, 3, tape, 0);
return 0;
]</langsyntaxhighlight>
 
Output:
Line 7,647 ⟶ 8,664:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp"># Finite state machine
(de turing (Tape Init Halt Blank Rules Verbose)
(let
Line 7,722 ⟶ 8,739:
(println '1s: (cnt '((X) (= 1 X)) Tape)) )
(bye)</langsyntaxhighlight>
{{out}}
<pre>"Simple incrementer"
Line 7,752 ⟶ 8,769:
===The universal machine===
Source for this example was lightly adapted from [https://bitbucket.org/ttmrichter/turing https://bitbucket.org/ttmrichter/turing]. This machine, because of Prolog's dynamic nature, has to check its configuration and the rules' compliance to the same at run-time. This is the role of all but the first of the <code>memberchk/2</code> predicates. In addition, calling the user-supplied rules has to be wrapped in a <code>once/1</code> wrapper because there is no way to guarantee in advance that the rules provided are deterministic. (An alternative to doing this is to simply allow <code>perform/5</code> to be non-deterministic or to check for multiple results and report an error on such.)
<langsyntaxhighlight lang="prolog">turing(Config, Rules, TapeIn, TapeOut) :-
call(Config, IS, _, _, _, _),
perform(Config, Rules, IS, {[], TapeIn}, {Ls, Rs}),
Line 7,782 ⟶ 8,799:
 
right(L, [], [B|L], [], B).
right(L, [S|Rs], [S|L], Rs, _).</langsyntaxhighlight>
===The incrementer machine===
<langsyntaxhighlight lang="prolog">incrementer_config(IS, FS, RS, B, S) :-
IS = q0, % initial state
FS = [qf], % halting states
Line 7,793 ⟶ 8,810:
incrementer(q0, b, 1, stay, qf).
 
turing(incrementer_config, incrementer, [1, 1, 1], TapeOut).</langsyntaxhighlight>
This will, on execution, fill TapeOut with [1, 1, 1, 1].
===The busy beaver machine===
<langsyntaxhighlight lang="prolog">busy_beaver_config(IS, FS, RS, B, S) :-
IS = 'A', % initial state
FS = ['HALT'], % halting states
Line 7,809 ⟶ 8,826:
busy_beaver('C', 1, 1, stay, 'HALT').
 
turing(busy_beaver_config, busy_beaver, [], TapeOut).</langsyntaxhighlight>
This will, on execution, fill TapeOut with [1, 1, 1, 1, 1, 1].
 
=={{header|Python}}==
{{trans|Perl}}
<langsyntaxhighlight lang="python">from __future__ import print_function
 
def run_utm(
Line 7,901 ⟶ 8,918:
)
)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
;;;=============================================================
Line 8,002 ⟶ 9,019:
(match-lambda ['(a b) '(c d e)] ... [x x])
l start))))
</syntaxhighlight>
</lang>
 
The resulting Turing Machine is a function that maps the initial tape record to the final one, so that several machines could run one after another or composed as any other functions
Line 8,009 ⟶ 9,026:
 
The simple incrementer:
<langsyntaxhighlight lang="racket">
(define INC
(Turing-Machine #:start 'q0
[q0 1 1 right q0]
[q0 () 1 stay qf]))
</syntaxhighlight>
</lang>
<pre>
> (INC '(1 1 1))
Line 8,028 ⟶ 9,045:
 
The incrementer for binary numbers
<langsyntaxhighlight lang="racket">
(define ADD1
(Turing-Machine #:start 'Start
Line 8,037 ⟶ 9,054:
[Add 1 0 left Add]
[Add () 1 stay End]))
</syntaxhighlight>
</lang>
<pre>
> (ADD1 '(1 1 0))
Line 8,071 ⟶ 9,088:
 
The busy beaver
<langsyntaxhighlight lang="racket">
(define BEAVER
(Turing-Machine #:start 'a
Line 8,080 ⟶ 9,097:
[c () 1 left b]
[c 1 1 stay halt]))
</syntaxhighlight>
</lang>
<pre>
> (BEAVER '(()))
Line 8,102 ⟶ 9,119:
 
The sorting machine
<langsyntaxhighlight lang="racket">
(define SORT
(Turing-Machine #:start 'A
Line 8,119 ⟶ 9,136:
[E 1 1 left E]
[E () () right STOP]))
</syntaxhighlight>
</lang>
<pre>
> (SORT '(2 1 2 2 2 1 1))
Line 8,171 ⟶ 9,188:
{{trans|Perl}}
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line>sub run_utm(:$state! is copy, :$blank!, :@rules!, :@tape = [$blank], :$halt, :$pos is copy = 0) {
$pos += @tape if $pos < 0;
die "Bad initial position" unless $pos ~~ ^@tape;
Line 8,254 ⟶ 9,271:
[< E 0 0 right STOP >]
];
</syntaxhighlight>
</lang>
 
{{out}}
Line 8,417 ⟶ 9,434:
Minimal error checking is done, but if no rule is found to be applicable, an appropriate error message is issued.
===incrementer machine===
<langsyntaxhighlight lang="rexx">/*REXX program executes a Turing machine based on initial state, tape, and rules. */
state = 'q0' /*the initial Turing machine state. */
term = 'qf' /*a state that is used for a halt. */
Line 8,460 ⟶ 9,477:
pad=left('', length( word( arg(1),2 ) ) \==1 ) /*padding for rule*/
rule.rules=arg(1); say right('rule' rules, 20) "═══►" rule.rules
return</langsyntaxhighlight>
'''output'''
<pre>
Line 8,472 ⟶ 9,489:
 
===three-state busy beaver===
<langsyntaxhighlight lang="rexx">/*REXX program executes a Turing machine based on initial state, tape, and rules. */
state = 'a' /*the initial Turing machine state. */
term = 'halt' /*a state that is used for a halt. */
Line 8,486 ⟶ 9,503:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
TM: ∙∙∙ </langsyntaxhighlight>
'''output'''
<pre>
Line 8,502 ⟶ 9,519:
 
===five-state busy beaver===
<langsyntaxhighlight lang="rexx">/*REXX program executes a Turing machine based on initial state, tape, and rules. */
state = 'A' /*initialize the Turing machine state.*/
term = 'H' /*a state that is used for the halt. */
Line 8,520 ⟶ 9,537:
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
TM: ∙∙∙ </langsyntaxhighlight>
'''output'''
<pre>
Line 8,552 ⟶ 9,569:
 
===stress sort===
<langsyntaxhighlight lang="rexx">/*REXX program executes a Turing machine based on initial state, tape, and rules. */
state = 'A' /*the initial Turing machine state. */
term = 'halt' /*a state that is used for the halt. */
Line 8,574 ⟶ 9,591:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
TM: ∙∙∙ </langsyntaxhighlight>
'''output'''
<pre>
Line 8,599 ⟶ 9,616:
=={{header|Ruby}}==
===The universal machine===
<langsyntaxhighlight lang="ruby">class Turing
class Tape
def initialize(symbols, blank, starting_tape)
Line 8,660 ⟶ 9,677:
return @tape.get_tape
end
end</langsyntaxhighlight>
 
===The incrementer machine===
<langsyntaxhighlight lang="ruby">incrementer_rules = {
:q0 => { 1 => [1, :right, :q0],
:b => [1, :stay, :qf]}
Line 8,674 ⟶ 9,691:
incrementer_rules, # operating rules
[1, 1, 1]) # starting tape
print t.run, "\n"</langsyntaxhighlight>
 
===The busy beaver machine===
<langsyntaxhighlight lang="ruby">busy_beaver_rules = {
:a => { 0 => [1, :right, :b],
1 => [1, :left, :c]},
Line 8,692 ⟶ 9,709:
busy_beaver_rules, # operating rules
[]) # starting tape
print t.run, "\n"</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::collections::VecDeque;
use std::fmt::{Display, Formatter, Result};
 
Line 8,837 ⟶ 9,854:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,870 ⟶ 9,887:
A simple implementation of Universal Turing Machine in Scala:
 
<langsyntaxhighlight lang="scala">
package utm.scala
 
Line 9,097 ⟶ 10,114:
}
 
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 9,122 ⟶ 10,139:
13: halt(): [ 1 1 1˅1 1 1]
Finished in the final state: halt()
</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
'''The Implementation'''
<syntaxhighlight lang="scheme">;----------------------------------------------------------------------------------------------
 
; The tape is a doubly-linked list of "cells". Each cell is a pair in which the cdr points
; to the cell on its right, and the car is a vector containing: 0: the value of the cell;
; 1: pointer to the cell on this cell's left; 2: #t if the cell has never been written.
 
; Make a new cell with the given contents, but linked to no other cell(s).
; (This is the only place that a cell can be marked as un-written.)
(define make-cell
(lambda (val . opt-unwrit)
(list (vector val '() (if (pair? opt-unwrit) (car opt-unwrit) #f)))))
 
; Return the un-written flag of the cell.
(define cell-unwrit?
(lambda (cell)
(vector-ref (car cell) 2)))
 
; Return the value of the cell.
(define cell-get
(lambda (cell)
(vector-ref (car cell) 0)))
 
; Store the value of the cell.
; Clears the un-written flag of the cell.
(define cell-set!
(lambda (cell val)
(vector-set! (car cell) 0 val)
(vector-set! (car cell) 2 #f)))
 
; Return the cell to the right of the given cell on the tape.
; Returns () if there is no cell to the right.
(define cell-right
(lambda (cell)
(cdr cell)))
 
; Return the cell to the left of the given cell on the tape.
; Returns () if there is no cell to the left.
(define cell-left
(lambda (cell)
(vector-ref (car cell) 1)))
 
; Return the cell to the right of the given cell on the tape.
; Extends the tape with the give blank symbol if there is no cell to the right.
; Optionally, passes the given un-written flag to make-cell (if needed).
(define cell-extend-right
(lambda (cell blank . opt-unwrit)
(if (null? (cdr cell))
(let ((new (if (pair? opt-unwrit) (make-cell blank (car opt-unwrit)) (make-cell blank))))
(vector-set! (car new) 1 cell)
(set-cdr! cell new)
new)
(cell-right cell))))
 
; Return the cell to the left of the given cell on the tape.
; Extends the tape with the give blank symbol if there is no cell to the left.
; Optionally, passes the given un-written flag to make-cell (if needed).
(define cell-extend-left
(lambda (cell blank . opt-unwrit)
(if (null? (vector-ref (car cell) 1))
(let ((new (if (pair? opt-unwrit) (make-cell blank (car opt-unwrit)) (make-cell blank))))
(set-cdr! new cell)
(vector-set! (car cell) 1 new)
new)
(cell-left cell))))
 
; Make a new tape whose cells contain the values in the given list.
; Optionally, pad the tape per the given blank symbol, left-padding and right-padding amounts.
(define make-tape
(lambda (values . opt-pads)
(unless (pair? values) (error 'make-tape "values argument is not a list" pads))
(let* ((tape (make-cell (car values)))
(last (do ((values (cdr values) (cdr values))
(cell tape (cell-extend-right cell (car values))))
((null? values) cell))))
(when (pair? opt-pads)
(let ((blank (list-ref opt-pads 0))
(left (list-ref opt-pads 1))
(right (list-ref opt-pads 2)))
(unless (and (integer? left) (integer? right))
(error 'make-tape "padding arguments must be integers" opt-pads))
(do ((count 0 (1+ count))
(cell last (cell-extend-right cell blank #t)))
((>= count right)))
(do ((count 0 (1+ count))
(cell tape (cell-extend-left cell blank #t)))
((>= count left)))))
tape)))
 
; Make a deep copy of the given tape.
; Note: Only copies from the given cell forward.
(define tape-copy
(lambda (tape)
(let ((copy (make-cell (cell-get tape))))
(do ((tape (cdr tape) (cdr tape))
(cell copy (cell-extend-right cell (cell-get tape))))
((null? tape)))
copy)))
 
; Return the first cell on a tape.
; Optionally, leading blank symbols are not included (will return last cell of blank tape).
(define tape-fst
(lambda (cell . opt-blank)
(let ((fst (do ((fst cell (cell-left fst))) ((null? (cell-left fst)) fst))))
(if (null? opt-blank)
fst
(do ((fst fst (cell-right fst)))
((or (null? (cell-right fst)) (not (eq? (car opt-blank) (cell-get fst)))) fst))))))
 
; Return the last cell on a tape.
; Optionally, trailing blank symbols are not included (will return first cell of blank tape).
(define tape-lst
(lambda (cell . opt-blank)
(let ((lst (do ((lst cell (cell-right lst))) ((null? (cell-right lst)) lst))))
(if (null? opt-blank)
lst
(do ((lst lst (cell-left lst)))
((or (null? (cell-left lst)) (not (eq? (car opt-blank) (cell-get lst)))) lst))))))
 
; Return true if the given tape is empty. (I.e. contains nothing but blank symbols.)
(define tape-empty?
(lambda (cell blank)
(let ((fst (tape-fst cell blank)))
(and (null? (cell-right fst)) (eq? blank (cell-get fst))))))
 
; Convert the contents of a tape to a string.
; Place a mark around the indicated cell (if any match).
; Prints the entire contents regardless of which cell is given.
; Optionally, leading and trailing instances of the given blank symbol are suppressed.
; The values of un-written cells are not shown, though space for them is included.
(define tape->string
(lambda (cell mark . opt-blank)
(let ((strlst (list #\[))
(marked-prev #f)
(fst (if (null? opt-blank) (tape-fst cell) (tape-fst cell (car opt-blank))))
(lst (if (null? opt-blank) (tape-lst cell) (tape-lst cell (car opt-blank)))))
(do ((cell fst (cell-right cell)))
((eq? cell (cell-right lst)))
(let* ((mark-now (eq? cell mark))
(fmtstr (cond (mark-now " {~a}") (marked-prev " ~a") (else " ~a")))
(value (if (and (not mark-now) (cell-unwrit? cell)) " " (cell-get cell))))
(set! strlst (append strlst (string->list (format fmtstr value))))
(set! marked-prev mark-now)))
(list->string (append strlst (string->list (if marked-prev " ]" " ]")))))))
 
;----------------------------------------------------------------------------------------------
 
; A Turing Machine contains the 7-tuple that formally defines it, stored in an array to
; make access relatively fast. The transitions are stored in an association list keyed by
; the pair (q_i . s_j) for ease of lookup.
 
; Make a new Turing Machine from the given arguments:
; Symbols list, blank symbol, input symbols list, states list, initial state, final (accepting)
; states list, and list of transitions. A transition is a 5-element list of: state (q_i),
; symbol read (s_i), symbol to write (s_ij), direction to move (d_ij), and next state (q_ij).
(define make-turing
(lambda (symbols blank inputs states initial finals . transitions)
; Raise error if any element in list lst is not in list set.
(define all-list-in-set
(lambda (set lst msg)
(for-each (lambda (val) (unless (memq val set) (error 'make-turing msg val))) lst)))
; Raise error if the given transition is not correctly formed.
(define transition-validate
(lambda (tran)
(when (or (not (list? tran)) (not (= 5 (length tran))))
(error 'make-turing "transition not a length-5 list" tran))
(let ((q_i (list-ref tran 0))
(s_j (list-ref tran 1))
(s_ij (list-ref tran 2))
(d_ij (list-ref tran 3))
(q_ij (list-ref tran 4)))
(unless (memq q_i states) (error 'make-turing "q_i not in states" q_i))
(unless (memq s_j symbols) (error 'make-turing "s_j not in symbols" s_j))
(unless (memq s_ij symbols) (error 'make-turing "s_ij not in symbols" s_ij))
(unless (memq d_ij '(L R N)) (error 'make-turing "d_ij not in {L R N}" d_ij))
(unless (memq q_ij states) (error 'make-turing "q_ij not in states" q_ij)))))
; Convert the given transitions list into an alist of transitions keyed by (q_i . s_j).
(define transitions-alist
(lambda (trns)
(cond ((null? trns) '())
(else (cons (cons (cons (caar trns) (cadar trns)) (list (cddar trns)))
(transitions-alist (cdr trns)))))))
; Validate all the arguments.
(unless (list? symbols) (error 'make-turing "symbols not a list" symbols))
(unless (memq blank symbols) (error 'make-turing "blank not in symbols" blank))
(all-list-in-set symbols inputs "inputs not all in symbols")
(unless (list? states) (error 'make-turing "states not a list" states))
(unless (memq initial states) (error 'make-turing "initial not in states" initial))
(all-list-in-set states finals "finals not all in states")
(for-each (lambda (tran) (transition-validate tran)) transitions)
; Construct and return the Turing Machine tuple vector.
(let ((tuple (make-vector 7)))
(vector-set! tuple 0 symbols)
(vector-set! tuple 1 blank)
(vector-set! tuple 2 inputs)
(vector-set! tuple 3 states)
(vector-set! tuple 4 initial)
(vector-set! tuple 5 finals)
(vector-set! tuple 6 (transitions-alist transitions))
tuple)))
 
; Return the symbols of a Turing Machine.
(define-syntax turing-symbols (syntax-rules () ((_ tm) (vector-ref tm 0))))
 
; Return the blank symbol of a Turing Machine.
(define-syntax turing-blank (syntax-rules () ((_ tm) (vector-ref tm 1))))
 
; Return the input symbols of a Turing Machine.
(define-syntax turing-inputs (syntax-rules () ((_ tm) (vector-ref tm 2))))
 
; Return the states of a Turing Machine.
(define-syntax turing-states (syntax-rules () ((_ tm) (vector-ref tm 3))))
 
; Return the initial state of a Turing Machine.
(define-syntax turing-initial (syntax-rules () ((_ tm) (vector-ref tm 4))))
 
; Return the final states of a Turing Machine.
(define-syntax turing-finals (syntax-rules () ((_ tm) (vector-ref tm 5))))
 
; Return the transitions of a Turing Machine.
(define-syntax turing-transitions (syntax-rules () ((_ tm) (vector-ref tm 6))))
 
; Return the q_i (current state) of alist element transition.
(define-syntax tran-q_i (syntax-rules () ((_ atran) (car (car atran)))))
 
; Return the s_j (symbol read from the tape) of alist element transition.
(define-syntax tran-s_j (syntax-rules () ((_ atran) (cdr (car atran)))))
 
; Return the s_ij (symbol written) of alist element transition.
(define-syntax tran-s_ij (syntax-rules () ((_ atran) (car (cadr atran)))))
 
; Return the d_ij (direction of move) of alist element transition.
(define-syntax tran-d_ij (syntax-rules () ((_ atran) (cadr (cadr atran)))))
 
; Return the q_ij (state transition) of alist element transition.
(define-syntax tran-q_ij (syntax-rules () ((_ atran) (caddr (cadr atran)))))
 
; Lookup the transition matching the given state and symbol in the given Turing Machine.
(define atrns-lookup
(lambda (state symbol tm)
(assoc (cons state symbol) (turing-transitions tm))))
 
; Convert the given Turing Machine transition to a string.
(define tran->string
(lambda (atran)
(format "(~a ~a ~a ~a ~a)"
(tran-q_i atran) (tran-s_j atran) (tran-s_ij atran) (tran-d_ij atran) (tran-q_ij atran))))
 
; Convert the given Turing Machine definition to a string.
; Options (zero or more) are, in order: component prefix string (default "");
; component suffix string (default ""); component separator string (default newline).
(define turing->string
(lambda (tm . opts)
(let ((prestr (if (> (length opts) 0) (list-ref opts 0) ""))
(sufstr (if (> (length opts) 1) (list-ref opts 1) ""))
(sepstr (if (> (length opts) 2) (list-ref opts 2) (make-string 1 #\newline)))
(strlst '()))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (turing-symbols tm) sufstr sepstr))))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (turing-blank tm) sufstr sepstr))))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (turing-inputs tm) sufstr sepstr))))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (turing-states tm) sufstr sepstr))))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (turing-initial tm) sufstr sepstr))))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (turing-finals tm) sufstr
(if (> (length (turing-transitions tm)) 0) sepstr "")))))
(do ((index 0 (1+ index)))
((>= index (length (turing-transitions tm))))
(set! strlst (append strlst (string->list
(format "~a~a~a~a" prestr (tran->string (list-ref (turing-transitions tm) index)) sufstr
(if (< index (1- (length (turing-transitions tm)))) sepstr ""))))))
(list->string strlst))))
 
;----------------------------------------------------------------------------------------------
 
; Run the given Turing Machine on the given input tape.
; If specified, display log of progress. Optionally, abort after given number of iterations.
; Returns the count of iterations, the accepting state (if one; else void), and the output
; tape as multiple values.
(define turing-run
(lambda (tm cell show-log? . opt-abort)
; Validate contents of input tape. (Leading/trailing blanks allowed; internals are not.)
(unless (tape-empty? cell (turing-blank tm))
(let ((fst (tape-fst cell (turing-blank tm)))
(lst (tape-lst cell (turing-blank tm))))
(if (eq? fst lst)
(unless (memq (cell-get fst) (turing-symbols tm))
(error 'turing-run "input tape has disallowed content" (cell-get fst)))
(do ((cell fst (cell-right cell)))
((eq? cell (cell-right lst)))
(unless (memq (cell-get cell) (turing-inputs tm))
(error 'turing-run "input tape has disallowed content" (cell-get cell)))))))
; Initialize state and head.
(let ((state (turing-initial tm)) (head cell) (atran #f)
(abort (and (pair? opt-abort) (integer? (car opt-abort))
(> (car opt-abort) 0) (car opt-abort))))
; Loop until no transition matches state/symbol or reached a final state.
(do ((count 0 (1+ count))
(atran (atrns-lookup state (cell-get head) tm)
(atrns-lookup state (cell-get head) tm)))
((or (not atran) (memq state (turing-finals tm)) (and abort (>= count abort)))
; Display final progress (optional).
(when show-log?
(let* ((string (format "~a" state))
(strlen (string-length string))
(padlen (max 1 (- 25 strlen)))
(strpad (make-string padlen #\ )))
(printf "~a~a~a~%" string strpad (tape->string cell head))))
; Return resultant count, accepting state (or void), and tape.
(values count (if (memq state (turing-finals tm)) state (void)) head))
; Display progress (optional).
(when show-log?
(let* ((string (format "~a ~a -> ~a ~a ~a" state (cell-get head)
(tran-s_ij atran) (tran-d_ij atran) (tran-q_ij atran)))
(strlen (string-length string))
(padlen (max 1 (- 25 strlen)))
(strpad (make-string padlen #\ )))
(printf "~a~a~a~%" string strpad (tape->string cell head))))
; Iterate.
(cell-set! head (tran-s_ij atran))
(set! state (tran-q_ij atran))
(set! head (case (tran-d_ij atran)
((L) (cell-extend-left head (turing-blank tm)))
((R) (cell-extend-right head (turing-blank tm)))
((N) head)))))))
 
;----------------------------------------------------------------------------------------------</syntaxhighlight>
'''Test Runner'''
<syntaxhighlight lang="scheme">;----------------------------------------------------------------------------------------------
 
; Run specified tests: A caption string, a Turing machine, a list of tests, and options (if
; 'notm present, do not output the Turing Machine definition (otherwise display it); if 'supp
; present, suppress leading/trailing blanks; 'mark present, mark the output tape; if 'supp
; present, suppress leading/trailing blanks; if 'leng present, print only the length of the
; output tape, not the contents of either; if 'show present, show an empty input tape (by
; default empty inputs are not shown)). A test is a list of: limit count (0 = unlimited),
; #t to log progress, and the input tape.
(define run-tm-tests
(lambda (caption tm test-lst . opts)
(printf "~%~a...~%" caption)
(unless (memq 'notm opts) (printf "~%~a~%" (turing->string tm)))
(let ((input #f))
(let loop ((tests test-lst))
(unless (null? tests)
(newline)
(set! input (tape-copy (caddar tests)))
(let-values (((count accepting output)
(turing-run tm (caddar tests) (cadar tests) (caar tests))))
(if (memq 'leng opts)
(printf "count = ~d~%accept = ~a~%output length = ~d~%"
count accepting (length output))
(let ((instr (if (memq 'supp opts)
(tape->string input #f (turing-blank tm))
(tape->string input #f)))
(outstr (if (memq 'supp opts)
(tape->string output (if (memq 'mark opts) output #f)
(turing-blank tm))
(tape->string output (if (memq 'mark opts) output #f)))))
(printf "count = ~d~%accept = ~a~%" count accepting)
(when (or (memq 'show opts) (not (tape-empty? input (turing-blank tm))))
(printf "input = ~a~%" instr))
(printf "output = ~a~%" outstr))))
(loop (cdr tests)))))))
 
;----------------------------------------------------------------------------------------------</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="scheme">(run-tm-tests
"Simple incrementer"
(make-turing
'(B 1)
'B
'(1)
'(q0 qf)
'q0
'(qf)
'(q0 1 1 R q0)
'(q0 B 1 N qf))
(list
(list 0 #t (make-tape '(1 1 1)))
(list 0 #t (make-tape '(B)))
) 'notm 'mark)
 
(run-tm-tests
"Three-state busy beaver"
(make-turing
'(0 1)
'0
'()
'(a b c halt)
'a
'(halt)
'(a 0 1 R b)
'(a 1 1 L c)
'(b 0 1 L a)
'(b 1 1 R b)
'(c 0 1 L b)
'(c 1 1 N halt))
(list
(list 0 #t (make-tape '(0) 0 3 2)) ; padding determined empirically
) 'notm 'mark)
 
(run-tm-tests
"5-state 2-symbol probable busy beaver"
(make-turing
'(0 1)
'0
'()
'(A B C D E H)
'A
'(H)
'(A 0 1 R B)
'(A 1 1 L C)
'(B 0 1 R C)
'(B 1 1 R B)
'(C 0 1 R D)
'(C 1 0 L E)
'(D 0 1 L A)
'(D 1 1 L D)
'(E 0 1 N H)
'(E 1 0 L A))
(list
(list 0 #f (make-tape '(0)))
) 'notm 'leng)</syntaxhighlight>
{{out}}
<pre style="height: 75ex; overflow: scroll">
Simple incrementer...
 
q0 1 -> 1 R q0 [ {1} 1 1 ]
q0 1 -> 1 R q0 [ 1 {1} 1 ]
q0 1 -> 1 R q0 [ 1 1 {1} ]
q0 B -> 1 N qf [ 1 1 1 {B} ]
qf [ 1 1 1 {1} ]
count = 4
accept = qf
input = [ 1 1 1 ]
output = [ 1 1 1 {1} ]
 
q0 B -> 1 N qf [ {B} ]
qf [ {1} ]
count = 1
accept = qf
output = [ {1} ]
 
Three-state busy beaver...
 
a 0 -> 1 R b [ {0} ]
b 0 -> 1 L a [ 1 {0} ]
a 1 -> 1 L c [ {1} 1 ]
c 0 -> 1 L b [ {0} 1 1 ]
b 0 -> 1 L a [ {0} 1 1 1 ]
a 0 -> 1 R b [ {0} 1 1 1 1 ]
b 1 -> 1 R b [ 1 {1} 1 1 1 ]
b 1 -> 1 R b [ 1 1 {1} 1 1 ]
b 1 -> 1 R b [ 1 1 1 {1} 1 ]
b 1 -> 1 R b [ 1 1 1 1 {1} ]
b 0 -> 1 L a [ 1 1 1 1 1 {0} ]
a 1 -> 1 L c [ 1 1 1 1 {1} 1 ]
c 1 -> 1 N halt [ 1 1 1 {1} 1 1 ]
halt [ 1 1 1 {1} 1 1 ]
count = 13
accept = halt
output = [ 1 1 1 {1} 1 1 ]
 
5-state 2-symbol probable busy beaver...
 
count = 47176870
accept = H
output length = 12289
</pre>
'''More Examples'''
<syntaxhighlight lang="scheme">(run-tm-tests
"Sorting test"
(make-turing
'(0 1 2 3)
'0
'(1 2)
'(A B C D E STOP)
'A
'(STOP)
'(A 1 1 R A)
'(A 2 3 R B)
'(A 0 0 L E)
'(B 1 1 R B)
'(B 2 2 R B)
'(B 0 0 L C)
'(C 1 2 L D)
'(C 2 2 L C)
'(C 3 2 L E)
'(D 1 1 L D)
'(D 2 2 L D)
'(D 3 1 R A)
'(E 1 1 L E)
'(E 0 0 R STOP))
(list
(list 0 #t (make-tape '(2 2 2 1 2 2 1 2 1 2 1 2 1 2) 0 1 1)) ; padding determined empirically
) 'notm 'supp)
 
(run-tm-tests
"Duplicate sequence of 1s"
(make-turing
'(0 1)
'0
'(1)
'(s1 s2 s3 s4 s5 H)
's1
'(H)
'(s1 0 0 N H)
'(s1 1 0 R s2)
'(s2 0 0 R s3)
'(s2 1 1 R s2)
'(s3 0 1 L s4)
'(s3 1 1 R s3)
'(s4 0 0 L s5)
'(s4 1 1 L s4)
'(s5 0 1 R s1)
'(s5 1 1 L s5))
(list
(list 0 #t (make-tape '(1 1 1) 0 0 4)) ; padding determined empirically
) 'notm 'supp)
 
(run-tm-tests
"Turing's first example from On Computable Numbers"
(make-turing
'(_ 0 1)
'_
'(_)
'(b c e f)
'b
'()
'(b _ 0 R c)
'(c _ _ R e)
'(e _ 1 R f)
'(f _ _ R b))
(list
(list 20 #t (make-tape '(_)))
) 'notm 'mark)
 
(run-tm-tests
"Palindrome checker"
(make-turing
'(_ 1 2)
'_
'(1 2)
'(br r1 e1 r2 e2 wl odd even)
'br
'(odd even)
; branch to look for 1 or 2 at end
'(br 1 _ R r1)
'(br 2 _ R r2)
'(br _ _ N even)
; walk right to end for 1
'(r1 1 1 R r1)
'(r1 2 2 R r1)
'(r1 _ _ L e1)
; check end symbol for 1
'(e1 1 _ L wl)
'(e1 _ _ N odd)
; walk right to end for 2
'(r2 2 2 R r2)
'(r2 1 1 R r2)
'(r2 _ _ L e2)
; check end symbol for 2
'(e2 2 _ L wl)
'(e2 _ _ N odd)
; walk left to beginning
'(wl 1 1 L wl)
'(wl 2 2 L wl)
'(wl _ _ R br))
(list
(list 0 #t (make-tape '(1 2 1)))
(list 0 #t (make-tape '(1 2 2)))
(list 0 #t (make-tape '(1 1)))
(list 0 #t (make-tape '(2 1)))
(list 0 #t (make-tape '(1)))
(list 0 #f (make-tape '(2 1 1 1 2)))
(list 0 #f (make-tape '(2 1 1 2 2)))
(list 0 #f (make-tape '(1 1 2 2 1 1)))
(list 0 #f (make-tape '(1 1 2 2 1 2)))
) 'notm 'mark)</syntaxhighlight>
{{out}}
<pre style="height: 107ex; overflow: scroll">
Sorting test...
 
A 2 -> 3 R B [ {2} 2 2 1 2 2 1 2 1 2 1 2 1 2 ]
B 2 -> 2 R B [ 3 {2} 2 1 2 2 1 2 1 2 1 2 1 2 ]
B 2 -> 2 R B [ 3 2 {2} 1 2 2 1 2 1 2 1 2 1 2 ]
B 1 -> 1 R B [ 3 2 2 {1} 2 2 1 2 1 2 1 2 1 2 ]
B 2 ->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
r1 2 -> 2 R r1 [ _ {2} 1 ]
r1 1 -> 1 R r1 [ _ 2 {1} ]
r1 _ -> _ L e1 [ _ 2 1 {_} ]
e1 1 -> _ L wl [ _ 2 {1} _ ]
wl 2 -> 2 L wl [ _ {2} _ _ ]
wl _ -> _ R br [ {_} 2 _ _ ]
br 2 -> _ R r2 [ _ {2} _ _ ]
r2 _ -> _ L e2 [ _ _ {_} _ ]
e2 _ -> _ N odd [ _ {_} _ _ ]
odd [ _ {_} _ _ ]
count = 10
accept = odd
input = [ 1 2 1 ]
output = [ _ {_} _ _ ]
 
br 1 -> _ R r1 [ {1} 2 2 ]
r1 2 -> 2 R r1 [ _ {2} 2 ]
r1 2 -> 2 R r1 [ _ 2 {2} ]
r1 _ -> _ L e1 [ _ 2 2 {_} ]
e1 [ _ 2 {2} _ ]
count = 4
accept = #<void>
input = [ 1 2 2 ]
output = [ _ 2 {2} _ ]
 
br 1 -> _ R r1 [ {1} 1 ]
r1 1 -> 1 R r1 [ _ {1} ]
r1 _ -> _ L e1 [ _ 1 {_} ]
e1 1 -> _ L wl [ _ {1} _ ]
wl _ -> _ R br [ {_} _ _ ]
br _ -> _ N even [ _ {_} _ ]
even [ _ {_} _ ]
count = 6
accept = even
input = [ 1 1 ]
output = [ _ {_} _ ]
 
br 2 -> _ R r2 [ {2} 1 ]
r2 1 -> 1 R r2 [ _ {1} ]
r2 _ -> _ L e2 [ _ 1 {_} ]
e2 [ _ {1} _ ]
count = 3
accept = #<void>
input = [ 2 1 ]
output = [ _ {1} _ ]
 
br 1 -> _ R r1 [ {1} ]
r1 _ -> _ L e1 [ _ {_} ]
e1 _ -> _ N odd [ {_} _ ]
odd [ {_} _ ]
count = 3
accept = odd
input = [ 1 ]
output = [ {_} _ ]
 
count = 21
accept = odd
input = [ 2 1 1 1 2 ]
output = [ _ _ {_} _ _ _ ]
 
count = 15
accept = #<void>
input = [ 2 1 1 2 2 ]
output = [ _ _ 1 {2} _ _ ]
 
count = 28
accept = even
input = [ 1 1 2 2 1 1 ]
output = [ _ _ _ {_} _ _ _ ]
 
count = 7
accept = #<void>
input = [ 1 1 2 2 1 2 ]
output = [ _ 1 2 2 1 {2} _ ]
</pre>
 
Line 9,127 ⟶ 11,008:
This implemetnation is based on the Computing Machines introduced in Turing's 1936 paper [https://www.cs.virginia.edu/~robins/Turing_Paper_1936.pdf ON COMPUTABLE NUMBERS, WITH AN APPLICATION TO THE ENTSCHEIDUNGSPROBLEM]. With the exception of "skeleton tables".<br>
'''SequenceL Code:'''<br>
<langsyntaxhighlight lang="sequencel">//region Imports
 
import <Utilities/Conversion.sl>;
Line 9,344 ⟶ 11,225:
(CurrentConfig: mConfig.FinalConfig, CurrentPosition: newState.CurrentPosition, Tape: newState.Tape);
 
//endregion</langsyntaxhighlight>
 
'''C++ Driver Code:'''<br>
<langsyntaxhighlight lang="c">#include <iostream>
#include <fstream>
#include <string>
Line 9,413 ⟶ 11,294:
}
throw(errno);
}</langsyntaxhighlight>
 
'''Turing Machine Files'''<br />
Line 9,552 ⟶ 11,433:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func run_utm(state="", blank="", rules=[], tape=[blank], halt="", pos=0) {
 
if (pos < 0) {
Line 9,649 ⟶ 11,530:
%w(E 1 1 left E),
%w(E 0 0 right STOP),
]);</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Line 9,663 ⟶ 11,544:
 
 
<langsyntaxhighlight lang="sml">(*** Signatures ***)
 
signature TAPE = sig
Line 9,994 ⟶ 11,875:
val () = simulate_int sorting NONE
end
</syntaxhighlight>
</lang>
 
{{output}}
Line 10,081 ⟶ 11,962:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc turing {states initial terminating symbols blank tape rules {doTrace 1}} {
set state $initial
set idx 0
Line 10,117 ⟶ 11,998:
}
return [join $tape ""]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts "Simple incrementer"
puts TAPE=[turing {q0 qf} q0 qf {1 B} B "111" {
{q0 1 1 right q0}
Line 10,150 ⟶ 12,031:
{E 1 1 left E}
{E 0 0 right H}
} no]</langsyntaxhighlight>
{{out}}
<pre>
Line 10,197 ⟶ 12,078:
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell|4+}}
<langsyntaxhighlight lang="sh">#!/usr/bin/env bash
main() {
printf 'Simple Incrementer\n'
Line 10,262 ⟶ 12,143:
 
main "$@"
</syntaxhighlight>
</lang>
{{Output}}
<pre>Simple Incrementer
Line 10,288 ⟶ 12,169:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Option Base 1
Public Enum sett
name_ = 1
Line 10,400 ⟶ 12,281:
Set tap = New Collection
UTM fiveStateBB, tap, countOnly:=-1
End Sub</langsyntaxhighlight>{{out}}
<pre>Simple incrementer
==================
Line 10,438 ⟶ 12,319:
{{libheader|Wren-dynamic}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Enum, Tuple, Struct
import "./fmt" for Fmt
 
var Dir = Enum.create("Dir", ["LEFT", "RIGHT", "STAY"])
Line 10,591 ⟶ 12,472:
Rule.new("E", "1", "0", Dir.LEFT, "A")
]
).run(20)</langsyntaxhighlight>
 
{{out}}
Line 10,644 ⟶ 12,525:
=={{header|Yabasic}}==
{{trans|Lua}}
<langsyntaxhighlight Yabasiclang="yabasic">// Machine definitions
 
name = 1 : initState = 2 : endState = 3 : blank = 4 : countOnly = true
Line 10,756 ⟶ 12,637:
UTM(incrementer$, "111")
UTM(threeStateBB$, " ")
UTM(fiveStateBB$, " ", countOnly)</langsyntaxhighlight>
 
=={{header|zkl}}==
This uses a dictionary/hash to hold the tape, limiting the length to 64k.
{{Trans|D}}
<langsyntaxhighlight lang="zkl">var [const] D=Dictionary; // short cut
// blank symbol and terminating state(s) are Void
var Lt=-1, Sy=0, Rt=1; // Left, Stay, Right
Line 10,780 ⟶ 12,661:
tape[pos]=r[0];
return(self.fcn(r[2],tape,pos+r[1],rules,verbose,n+1));
}</langsyntaxhighlight>
D is a dictionary, SD is a small fixed (at runtime) dictionary
<langsyntaxhighlight lang="zkl">println("Simple incrementer");
turing("q0",D(0,Rt, 1,Rt, 2,Rt),0, // Incrementer
D("q0",D(1,T(1,Rt,"q0"), Void,T(1,Sy,Void)) ) );
Line 10,806 ⟶ 12,687:
"C",D(Void,T(1,Rt,"D"), 1,T(Void,Lt,"E")),
"D",D(Void,T(1,Lt,"A"), 1,T(1, Lt,"D")),
"E",D(Void,T(1,Sy,Void), 1,T(Void,Lt,"A")) ) ,False);</langsyntaxhighlight>
{{out}}
<pre>
9,487

edits