Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Brainfuck interpreter in Pipes
def push(stack, el): stack+(el,);
def pop(stack): (stack:take(len(stack)-1), stack:get(len(stack)-1));
def memset(state, key, value): (state |> @filter({0}!=key)) + ((key, value),);
def memget(state, key): state |> last({1}):if({0}==key)# ?? 0;
def memadd(state, key, value): memset(state, key, memget(state, key)+value);
def findclosing(code, i):
(1, i+1):unfold(fun(count, i):
i >= len(code) or count == 0 ? null,
code:get(i) == '[' ? (i, (count+1, i+1)),
code:get(i) == ']' ? (i, (count-1, i+1)),
(i, (count, i+1))
) |> :last;
def brainfuck(code, input=''):
(0, 0, 0, ((0, 0),):seq, (0,):seq):unfold(fun(i, j, ptr, mem, stack):
i>=len(code) ? null,
code:get(i) == '>' ? ('', (i+1, j, ptr+1, mem, stack)),
code:get(i) == '<' ? ('', (i+1, j, ptr-1, mem, stack)),
code:get(i) == '+' ? ('', (i+1, j, ptr, memadd(mem, ptr, 1), stack)),
code:get(i) == '-' ? ('', (i+1, j, ptr, memadd(mem, ptr, -1), stack)),
code:get(i) == '.' ? (chr(memget(mem, ptr)), (i+1, j, ptr, mem, stack)),
code:get(i) == ',' ? ('', (i+1, j+1, ptr, memset(mem, ptr, ord(input:get(j))), stack)),
code:get(i) == '[' ? ('', memget(mem, ptr) == 0 ?
(findclosing(code, i)+1, j, ptr, mem, stack),
(i+1, j, ptr, mem, push(stack, i)),
),
code:get(i) == ']' ? ('', pop(stack)->({1}, j, ptr, mem, {0})),
('', (i+1, j, ptr, mem, stack))
) |> :summary('');
=> brainfuck('++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.') as answer at the end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.