Execute Brain****: Difference between revisions

Added some comments and minor bugfix
(Added some comments and minor bugfix)
Line 3,040:
process_bf_chars(Instructions).
 
brain_from_file(File) :- % or from file...
read_file_to_codes(File, Codes, []),
maplist(char_code, Instructions, Codes),
Line 3,078:
!, % cuts are to force tail recursion, so big programs will run
instruction(NextI, NextCode, UpdatedMem).
 
% to loop, add the loop code to the start of the program then execute
% when the loop has finished it will reach itself again then can retest for zero
instruction(loop(LoopCode), Code, Mem) :-
caddr(Mem, X),
Line 3,090 ⟶ 3,093:
instruction(NextI, NextCode, Mem).
 
% memory is stored in two parts:
% 1. a list with the current address and everything after it
% 2. a list with the previous memory in reverse order
mem_instruction(next_addr, mem(Mb, [Caddr]), mem([Caddr|Mb], [0])).
mem_instruction(next_addr, mem(Mb, [Caddr,NextAddr|Rest]), mem([Caddr|Mb], [NextAddr|Rest])).
mem_instruction(prev_addr, mem([PrevAddr|RestOfPrev], Caddrs), mem(RestOfPrev, [PrevAddr|Caddrs])).
 
% wrap instructions at the byte boundaries as this is what most programmers expect to happen
mem_instruction(inc_caddr, MemIn, MemOut) :- caddr(MemIn, 255), update_caddr(MemIn, 0, MemOut).
mem_instruction(inc_caddr, MemIn, MemOut) :- caddr(MemIn, Val), succ(Val, IncVal), update_caddr(MemIn, IncVal, MemOut).
mem_instruction(dec_caddr, MemIn, MemOut) :- caddr(MemIn, 0), update_caddr(MemIn, 255, MemOut).
mem_instruction(dec_caddr, MemIn, MemOut) :- caddr(MemIn, Val), succ(DecVal, Val), update_caddr(MemIn, DecVal, MemOut).
 
% input and output
mem_instruction(out_caddr, Mem, Mem) :- caddr(Mem, Val), char_code(Char, Val), write(Char).
mem_instruction(in_caddr, MemIn, MemOut) :- get_single_char(Code), char_code(Char, Code), write(Char), update_caddr(MemIn, Code, MemOut).
get_single_char(Code),
char_code(Char, Code),
write(Char),
map_input_code(Code,MappedCode),
update_caddr(MemIn, MappedCode, MemOut).
 
% need to map the newline if it is not a proper newline character (system dependent).
map_input_code(13,10) :- nl.
map_input_code(C,C).
 
% The value at the current address
Anonymous user