Lesson 4: Methods

Beginner

Methods are reusable subprograms. A method has a name, a fixed number of inputs, and a fixed number of outputs. You define a method once and call it from anywhere — including from inside itself (recursion).

Anatomy of a method

Every method is a dataflow graph with two special nodes:

Inputs parameters arrive here ... your graph ... Outputs return values collected here

Method calls

A method-call node invokes another method. It looks like a regular node but in a purple color. Its name is the method being called. The node’s inputs map to the called method’s input bar, and its outputs come from the called method’s output bar.

fib method call

Walkthrough: Fibonacci

Load the Fibonacci example (Cmd+Shift+E > Math).

This project has two methods: fib and main.

main calls fib(10):

Inputs 10 n fib method call result Outputs returns 55

fib has two cases (more on cases in Lesson 5). The key idea: fib calls itself twice (fib(n-1) and fib(n-2)) and adds the results. This is recursion.

Methods and cases A method can have multiple cases. The engine tries case 1 first. If case 1 fails (via a control annotation), it tries case 2, and so on. This is how Phograph handles conditional logic — see Lesson 5.

Input and output counts

When you define a method, you specify how many inputs and outputs it has. The input bar gets that many output pins, and the output bar gets that many input pins. Every call site must match this arity.

Examples:

  Method "square":     1 input, 1 output   (x → x*x)
  Method "add":        2 inputs, 1 output  (a, b → a+b)
  Method "swap":       2 inputs, 2 outputs (a, b → b, a)
  Method "greet":      0 inputs, 0 outputs (side effect only)

Exercise 4.1 — Write a square method

  1. Create a new project.
  2. Add a method called square with 1 input and 1 output.
  3. Inside square: wire the input bar’s output to both inputs of a * node (fan-out). Wire the product to the output bar.
  4. Add a main method (0 inputs, 1 output).
  5. In main: add constant 7, wire it to a square method-call node, wire the result to the output bar.
  6. Run. The output should be 49.

Exercise 4.2 — Compose two methods

  1. Create a method double (1 input, 1 output) that multiplies its input by 2.
  2. In main: call double, then pass the result to square.
  3. Start with constant 3. The chain is: 3 → double → 6 → square → 36.
  4. Run. Output should be 36.

Exercise 4.3 — Two outputs

  1. Create a method divmod (2 inputs, 2 outputs) that returns the quotient and remainder of a / b.
  2. Inside: wire input 0 and input 1 to a / node for the quotient, and to a mod node for the remainder.
  3. Wire both results to the two output bar pins.
  4. Call divmod(17, 5) from main.
  5. Wire each output to a separate log. You should see 3 and 2.

Key Concepts