Subscribed unsubscribe Subscribe Subscribe

MATLAB BF Interpreter

MATLAB Memos

bfi.m

function ret = bfi(prog)
    m = zeros(1,1024);
    mp = 1;
    stdout = [];
    prog = regexprep(prog, '[^><\+-\[\]\.,]', '');
    prog = strrep(prog, '+', 'm(mp) = m(mp) + 1;');
    prog = strrep(prog, '-', 'm(mp) = m(mp) - 1;');
    prog = strrep(prog, '>', 'mp = mp + 1;');
    prog = strrep(prog, '<', 'mp = mp - 1;');
    prog = strrep(prog, '[', 'while (m(mp) ~= 0);');
    prog = strrep(prog, ']', 'end;');
    prog = strrep(prog, '.', 'stdout = [stdout m(mp)];');
    prog = strrep(prog, ',', 'm(mp) = input(char(98,102,105,62),char(115));');
    eval(prog);
    ret = char(stdout);
end

bfi2.m

function ret = bfi2(prog)
    mem = zeros(1,1024);
    memptr = 1;
    prgctr = 0;
    repstack = [];
    stdin = [];
    stdout = [];

    prog = regexprep(prog, '[^><\+-\[\]\.,]', '');
    while (prgctr < length(prog))
        disp(mem(1:20));
        prgctr = prgctr + 1;
        switch prog(prgctr)
            case '+'
                mem(memptr) = mem(memptr) + 1;
            case '-'
                mem(memptr) = mem(memptr) - 1;
            case '>'
                memptr = memptr + 1;
            case '<'
                memptr = memptr - 1;
            case '.'
                stdout = [stdout, mem(memptr)];
            case ','
                if length(stdin) == 0
                    disp(char(stdout));
                    disp(char(10));
                    stdin = [stdin input('bfi>', 's')];
                end
                mem(memptr) = stdin(1);
                stdin = stdin(2:end);
            case ']'
                prgctr = repstack(end) - 1;
                repstack = repstack(1:(end-1));
            case '['
                if(mem(memptr) ~= 0)
                    repstack = [repstack prgctr];
                else
                    nestlevel = 1;
                    for prgctr = (prgctr+1):length(prog)
                        switch prog(prgctr)
                            case '['
                                nestlevel = nestlevel + 1;
                            case ']'
                                nestlevel = nestlevel - 1;
                        end
                        if(nestlevel == 0)
                            break;
                        end
                    end
                end
        end
    end
    ret = char(stdout);
end