This is a challenge I thought of recently which I think is not hard but allows for a wide range of possible solutions. Seems like a perfect fit for the creativity of PPCG users :)
Define two functions which together form a lossless round-trip
String × String → String → String × String.
More specifically, define two functions
separate with repsective types
String × String → String and
String → String × String such that
separate ∘ combine = id.
Even more specifically, define two functions (or methods/procedures/etc), which I will refer to as
separate, and which exhibit the following characteristics:
When invoked with a single string,
separateproduces two strings as results. (You may use any reasonable string type. Most languages don't canonically allow producing multiple values, so feel free to to do something equivalent, such as returning a 2-tuple or modifying two global variables.)
When invoked with two strings,
combineproduces a single string as result. (You may accept input to
separatein the same form that
combineproduces, or any other reasonable form.)
For any two strings
separate(combine(a, b))must result in two strings which are (structurally) equivalent to
The above bullets are the only restrictions on
separate. So, for instance,
combine ∘ separateneed not be
separatecan even be a partial function, if you like.
(Defer to the final and more-verbose description if there are any ambiguities between the three)
My goal with this challenge is to inspire creative and interesting solutions. As such, in order to avoid priming/suggesting your thinking about how to solve this problem, I will not be providing test cases, and I strongly suggest that you do not look at the existing answers until you submit your own.
This challenge is a popularity-contest; the answer with the highest score at noon on April 5th, UTC, is the winner.
Guidelines for voters, included to be a valid popularity-contest, are as follows:
- Strongly prefer answers which you do not immediately comprehend, are not obviously correct, and/or surprise you
- Prefer answers which go beyond strings, i.e., those which make use of more than the problem statement did (functions, strings, pairs)
- Avoid answers which are similar to your own solution(s)
- Avoid answers which boil down to language builtins