I've just started teaching myself Scala to get my feet wet with functional programming, and I'm messing with around with some classical cryptography. The following code produces monoalphabetic simple substitution encryption, but I'm still trying to wrap my head around both Scala itself and functional style, so I'm sure this could be more concise and FP-oriented. For example, I'd love to get rid of var accumText
and use a val
instead, but I haven't been able to figure out how to make that work. Any advice on getting this more Scala-esque and FP-oriented would be greatly appreciated!
object SimpSub {
// alphabet array
private val alphabet = ('A' to 'Z').toList
def main(args: Array[String]) {
// split text into char list
val text = args(0).toUpperCase.toList
val key = args(1).toUpperCase.toList
def buildCipherAlphabet(): List[Char] = {
// build the cipher alphabet by concatenating the key to
// existing alphabet and removing duplicate letters
return (key ::: alphabet).distinct
}
def encipher(): List[Char] = {
// get the cipher alphabet
val newAlph = buildCipherAlphabet()
var accumText: String = ""
for (c <- text) {
// add in whitespace
if (c == ' ')
accumText += c
else
// add the letter of the cipher alphabet corresponding to the current character
// in the plaintext
accumText += newAlph(alphabet.indexOf(c))
}
val cipherText = accumText.toList
return cipherText
}
val cipherText = encipher()
println("Plaintext: " + args(0))
println("Key: " + args(1))
print("Ciphertext: ")
for (c <- cipherText)
print(c)
print("\n")
}
}