Use GPT-3 To Build A Code Translator
Once you know a programming language well, the process for learning a new language is not very hard. It is just time consuming. You need to read the documentation for basic syntax and flow control, get familiar with its idioms, memorize core parts of the standard libraries, and learn its tool chains. What can we do to speed up the learning process? One thing we can do is provide great examples in the documentation. Can we do better? What if you have working examples for every problem you encountered? What if you can describe your intents in a familiar language and see how it should look in a new language? As it turns out, GPT-3 is really good at this task.
I wanted to add a function to my .emacs file which takes a list of file names and return the first valid file. (I run Emacs on Windows, mac OS, and Linux, and they tend to put files in different places.) I know how to write code that does this in Java, Go, and Python. But, gosh, I have a hard time doing it in Emacs Lisp. GNU has extensive documentation for Emacs. But do I really want to read all of it?
Why don’t I ask GPT-3 to do this for me? I gave it the source code:
files = ["/tmp/a.txt", "/tmp/b.txt", "tmp/c.txt"]
next((f for f in files if os.path.isfile(f)), files[-1])
And it spit back:
;; Emacs Lisp
;; This code will return the first file in the list of files that is an existing file, or the last file in the list if none of the files exist.
(let ((files '("/tmp/a.txt" "/tmp/b.txt" "tmp/c.txt")))
(or (cl-some #'file-exists-p files) (car (last files))))
This was really nice! It taught me about cl-some
, file-exists-p
and provided a refresher on the use of the unintuitively named car
function.
It can be a bit hit-and-miss. This is not great translation:
// Go code
package main
import (
"os"
"path/filepath"
)
func main() {
files := []string{"/tmp/a.txt", "/tmp/b.txt", "tmp/c.txt"}
// next() is a function that returns the first element of an iterable that satisfies a given condition.
// In this case, it returns the first file in the files array that is a valid file path.
// If none of the files in the array are valid file paths, it returns the last element of the array.
nextFile := func() string {
for _, f := range files {
if _, err := os.Stat(f); err == nil {
return f
}
}
return files[len(files)-1]
}
println(nextFile())
}
Building the actual code translator is very simple. If you are using OpenAI’s Completion API, use a prompt like this
Translate the original code the target programming language. The target programming language is ${target_lanaguage}. The original code starts immediately after this line.
I continue to be delighted by the utilities of GPT-3. It is a great assistant for learning and I am excited to discover more ways to use it. My belief is that technology should be used to enhance human knowledge, not to replace it.