Python's pickle module is used for serialisation, allowing one to dump an object in a way such that it can be later reconstructed. For this, pickle uses a simple stack-based language.
To keep things simple, we will be dealing with a small subset of this language:
( Push a mark to the stack S'abc'\n Push a string to the stack (here with contents 'abc') l Pop everything up to the last mark, wrapping all but the mark in a list t Pop everything up to the last mark, wrapping all but the mark in a tuple . Terminate the virtual machine
Your task is to implement this subset of the language. Note that
\n is a literal newline here, and newlines are actually important to the language.
For those familiar with GolfScript or CJam-like languages,
l/t operate similarly to
To keep things simple, the input will always be valid. In particular, you may assume the following about the input:
- Strings will only consist of lowercase letters and spaces
[a-z ], and will always use single quotes.
- There will be no extraneous characters, with all instructions being as specified above. For example, this means that newlines will only ever occur after strings.
l/thas a matching
(before it and every
(has a matching
l/tafter it. There will also be at least one
- There will be exactly one
., and it will always be the final character.
You may take input via command line, STDIN or function argument. You may use a single newline-escaped string instead of a multiline string if you wish, but please specify this in your answer.
Output should be a representation of the final object, printed to STDOUT or returned as a string. Specifically:
Strings are represented by opening and closing single quotes with content in between, e.g.
S'abc' -> 'abc'. You may not use double quotes for this challenge, even though they are allowed in Python.
Lists are represented by comma-separated elements surrounded by
['a','b','c']), while tuples are repsented by comma-separated elements surrounded by
- Spaces don't matter, e.g.
('a', 'b', 'c' )is okay.
- You cannot have a comma before the closing bracket. Note that this is intentionally different from Python syntax rules to make things easier for most languages, and also to make it harder to simply build the list/tuple in Python then output it, due to how the single-element tuple is represented (for this challenge, we need
('a')as opposed to
The above text might seem daunting, but the following examples should make things a bit clearer.
(S'hello world' l.
(S'string one' S'string two' S'string three' t.
('string one', 'string two', 'string three')
(S'a' (S'b' S'c' lt.
((S'a' S'b' (lS'c' t(S'd' tl.
[('a', 'b', , 'c'), ('d')]
((S'a' ((S'b' t(S'c' lS'd' (((ltlS'e' S'f' lS'g' tl.
- This is code-golf, so the code in the fewest bytes wins.
- Any functionality that is designed to work with Python pickles is not allowed.
Security note: In real code, only unpickle from sources you trust, or else you might get a nasty
cos\nsystem\n(S'rm -rf'\ntR. surprise