Lab 2 -- String Encryptors
Purpose
Learn how to define functions, and about string library
Introduction
You’ve stumbled upon a malfunctioning encryption device that scrambles secret messages into code. Unfortunately, the documentation went missing! Your mission is to reverse-engineer each of the device’s 10 black-box functions so that you can replicate their behavior in Pyret.
How it works
The device exposes ten functions, named support.encryptor1 through support.encryptor10. Each encryptor takes in a String and returns a new, “encrypted” String. Alongside each encryptor, there’s a corresponding tester routine — support.test-encryptor1, support.test-encryptor2, and so on that — checks whether your replication matches the original for all possible inputs.
Instructions
- Experiment
- Call each support.encryptorN with a variety of sample strings.
- Observe how the output changes and identify the pattern or rule it applies.
- Keep a written log of the inputs you tried and the outputs you observed (your TA will ask you to justify these choices).
- Recreate
- Write your own function, for example,
that implements the same transformation you discovered. 3. Use Pyret’s String library functions (e.g. string-length, string-substring, string-index-of, etc.) to build your version.fun my-encryptor1(s :: String) -> String: ... end
- Verify
- Pass your function to the provided tester:
support.test-encryptor1(my-encryptor1)
If the tester completes without errors, your encryption logic is correct!
Here’s how we built an encryptor that returns only the first character of any string:
provide *
provide-types *
fun encryptor0(s :: String) -> String:
doc: "returns the first letter of the string"
string-substring(s, 0, 1)
end
check "encryptor0: empty str":
encryptor0("") raises "index"
end
check "encryptor0: general":
encryptor0("a") is "a"
encryptor0(" ") is " "
encryptor0("hello") is "h"
encryptor0("1, ") is "1"
end
More Hints!
- When choosing Strings to use as inputs to the encryptors, it will be useful to vary your inputs – think about why this could be. In what ways can you vary your Strings?
- Think about scenarios where we might see strings of text, such as a book or report. What symbols might you commonly see in that text, other than alphabetical letters?
- Remember that Strings in Pyret are 0-indexed. This means that the first character in a string will be assigned index 0 (not 1).
- Encryptor 9 is one of the trickiest. Try strings of various lengths that start with the same letters. What do you notice?