Two posts in two days? Madness!
Posts in StackLang:
But really, it got a bit late yesterday so I figured I’d split this into two different posts.
Two posts in two days? Madness!
But really, it got a bit late yesterday so I figured I’d split this into two different posts.
Let’s continue StackLang Part VII: New CLI and Datatypes and implement lists stacks in the compiler!
In this post:
We’ve gone through all sorts of things building up the StackLang language so far:
But what can we actually do with it?
It’s been a bit, but I hope it’s worth it. StackLang, part 5: compiling to C!
StackLang, part 4: an interpreter. Here we go again!
This time, the goal is to actually get code running
StackLang, part 3: parsing. This is going to be the most complicated one thus far! Onward.
StackLang, part 2: lexing.
It’s quite often the simplest part of implementing a programming language (although parsers for s-expression based languages come close), but it’s still something that needs done. So here we go!
I enjoy writing programming languages. Example: Tiny. Let’s do that again.
This time, StackLang:
{
@[n fact]
1
{ n 1 - $fact fact n * }
N 1 <= if
} @fact
5 $fact fact writeln
Bit of gibberish there, I suppose, but the goal is to write everything in a postfix/stack based model. So n 1 - $fact fact n *
is equivalent to fact(fact, n - 1) * n
in a more traditional language.
Over the next few posts, I hope to write up where I am thus far and what’s next.
Part 1: Implement a Turing machine defined as such:
Begin in state A. Perform a diagnostic checksum after 6 steps.
In state A: If the current value is 0: - Write the value 1. - Move one slot to the right. - Continue with state B. If the current value is 1: - Write the value 0. - Move one slot to the left. - Continue with state B.
…
> What is the final number of `1s` on the tape?
Most of this problem actually came down to reading the input:
```python
# Map of (current state, current value, key) -> value
# key is one of value, offset, state
transitions = {}
breakpoint = 0
state = None
pointer = 0
one_bits = set()
for line in lib.input():
line = line.strip('- ')
arg = line.split()[-1][:-1]
if arg == 'steps':
arg = line.split()[-2]
try:
arg = int(arg)
except:
pass
# Store values based on that argument
if line.startswith('Begin'):
state = arg
elif line.startswith('Perform'):
breakpoint = arg
elif line.startswith('In'):
current_state = arg
elif line.startswith('If'):
current_value = arg
elif line.startswith('Write'):
transitions[current_state, current_value, 'value'] = arg == 1
elif line.startswith('Move'):
transitions[current_state, current_value, 'offset'] = 1 if arg == 'right' else -1
elif line.startswith('Continue'):
transitions[current_state, current_value, 'state'] = arg
As we did in part 1 of day 22, we’ll use a set
to store the current state (store 1
, if an index is not in the set
, it’s 0
). That gives us the ability to grow unbounded (so long as we have enough RAM).