Knowledge card L2 · Context engineering informational

Generate a Function From a Clear Signature and Test

What it is

A generation move: hand ChatGPT the function signature and a couple of input/output examples, and let it write the body — instead of describing the behaviour in vague prose.

spec-first generationSignatureExample I/OChatGPT fills bodyRun the test
Give ChatGPT the contract and the test; let it fill the middle.

Why it works

A signature plus examples is an unambiguous contract. It removes the guesswork that makes generated code drift from what you meant, and the examples double as a test you can run immediately.

When to use it

Any self-contained function where you already know the interface: parsers, formatters, validators, small transforms. Best when you can state at least one concrete input and its expected output.

When not to use it

Skip it when the interface itself is the hard part — there, design the shape first. Prose-only prompts are fine for throwaway one-liners.

Prompt

Write this function.

Signature: <name(args) -> return>
Examples:
  <input> -> <output>
  <input> -> <output>
Constraints: <language, no deps, edge cases to handle>.

Return only the function and a one-line note on any assumption you made.

Example

Given slugify(title: str) -> str with two examples, ChatGPT returns a body that strips punctuation, collapses spaces, and lowercases — passing both examples on the first run.

Advanced version

Add a failing test as the example and ask ChatGPT to make it pass, then to add the two edge cases it thinks you forgot. This mirrors a real test-driven loop.

Common mistakes

  • Describing behaviour in adjectives ('make it robust') instead of showing input and output.
  • Accepting the body without running the example it was supposed to satisfy.
  • Bundling five functions into one prompt so you cannot tell which spec produced which bug.

Related