<!-- Functions · Tin · https://tin.ad/docs/learn/functions/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 3 of 34

# Functions

**Goal.** Write functions with typed parameters, one-line bodies, early returns and recursion.

## Defining a function

A function takes values in (its parameters) and gives one value back (its result). Every parameter has a
type, and so does the result.

*define.tin · tin run define.tin*

```tin
// fn name(parameter: type, ...): result type { body }
fn add(a: int, b: int): int {
  a + b                    // the last expression is the result
}

fn main() {
  print(add(2, 3))
  let total = add(add(1, 2), 10)
  print(total)
}
```

<!-- output -->
```text
5
13
```

There is no `return` at the end. In Tin, a block's last expression is its value, and a
function's body is a block. That one rule shows up everywhere, in `if` and `match` too.

## One-line functions

When the body is a single expression, write it after `=>` and skip the braces.

*arrow.tin · tin run arrow.tin*

```tin
fn square(x: int): int => x * x
fn greeting(name: string): string => "Hello, {name}!"

fn main() {
  print(square(12))
  print(greeting("Ada"))
}
```

<!-- output -->
```text
144
Hello, Ada!
```

## Functions that only do something

Leave out the result type when a function is there for what it does, like printing, rather than for a value.

*no-result.tin · tin run no-result.tin*

```tin
// No result type: the function does something instead of computing a value.
fn banner(title: string) {
  let line = "=".repeat(title.len + 4)
  print(line)
  print("| {title} |")
  print(line)
}

fn main() {
  banner("Tin")
}
```

<!-- output -->
```text
=======
| Tin |
=======
```

## Leaving early with return

`return` exits the function right away with a value. It's useful for handling the special cases
first, so the main case reads cleanly at the end.

*return.tin · tin run return.tin*

```tin
fn describe(n: int): string {
  if n < 0 { return "negative" }    // return leaves the function early
  if n == 0 { return "zero" }
  "positive"
}

fn main() {
  print(describe(-4))
  print(describe(0))
  print(describe(9))
}
```

<!-- output -->
```text
negative
zero
positive
```

## A function that calls itself

*recursion.tin · tin run recursion.tin*

```tin
// A function can call itself.
fn factorial(n: int): int => if n <= 1 { 1 } else { n * factorial(n - 1) }

fn main() {
  print(factorial(5))
  print(factorial(12))
}
```

<!-- output -->
```text
120
479001600
```

  factorial(13) is bigger than an int can hold, so it panics instead of printing a wrong number.

## Mistakes the compiler catches

Parameters always need types. This is what lets Tin check every call, and later it is how an agent's tools
get their schemas.

*param-types.tin · tin check param-types.tin*

```tin
fn add(a, b) => a + b

fn main() {
  print(add(1, 2))
}
```

<!-- compiler output -->
```text
error: expected ':' after parameter 'a' (parameters need types), found ','
 --> param-types.tin:1:9
  |
1 | fn add(a, b) => a + b
  |         ^
```

A call must pass every argument. The note shows the function's signature, so you don't have to look it up:

*arity.tin · tin check arity.tin*

```tin
fn add(a: int, b: int): int => a + b

fn main() {
  print(add(1))
}
```

<!-- compiler output -->
```text
error: add takes 2 argument(s), found 1
 --> arity.tin:4:9
  |
4 |   print(add(1))
  |         ^^^^^^
  = note: signature: add(a: int, b: int)
```

A function that promises an `int` must produce one on every path. An `if` without an
`else` has no value when the condition is false:

*missing-value.tin · tin check missing-value.tin*

```tin
fn bonus(score: int): int {
  if score > 100 { 10 }
}

fn main() {
  print(bonus(120))
}
```

<!-- compiler output -->
```text
error: 'bonus' must return int, but its body ends without a value
 --> missing-value.tin:1:1
  |
1 | fn bonus(score: int): int {
  | ^^^^^^^^
  = note: the last expression of a block is its value; or use `return`
```

## Tasks

### Task 1: The largest of three

Write `max3(a: int, b: int, c: int): int` and print it for `(3, 9, 4)`,
`(-1, -5, -2)` and `(7, 7, 7)`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```tin
fn max3(a: int, b: int, c: int): int {
  let ab = if a > b { a } else { b }
  if ab > c { ab } else { c }
}

fn main() {
  print(max3(3, 9, 4))
  print(max3(-1, -5, -2))
  print(max3(7, 7, 7))
}
```

<!-- output -->
```text
9
-1
7
```

### Task 2: Leap years

A year is a leap year if it divides by 4, except years that divide by 100, unless they also divide by
400. Write `isLeap(year: int): bool` as a one-line function and check 2024, 1900, 2000 and 2026.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```tin
// Divisible by 4, except centuries, except every 400 years.
fn isLeap(year: int): bool => year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)

fn main() {
  print("2024: {isLeap(2024)}")
  print("1900: {isLeap(1900)}")
  print("2000: {isLeap(2000)}")
  print("2026: {isLeap(2026)}")
}
```

<!-- output -->
```text
2024: true
1900: false
2000: true
2026: false
```

### Task 3: Every path needs a value

This doesn't compile. Read the error and fix `grade` so that scores below 75 get
`"C"`.

*task-3.tin · tin check task-3.tin*

```tin
fn grade(score: int): string {
  if score >= 90 { "A" }
  else if score >= 75 { "B" }
}

fn main() {
  print(grade(80))
}
```

<!-- compiler output -->
```text
error: branches have different types: string and void
 --> task-3.tin:2:3
  |
2 |   if score >= 90 { "A" }
  |   ^^^^^^^^^^^^^^^^^^^^^^
```

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```tin
fn grade(score: int): string {
  if score >= 90 { "A" }
  else if score >= 75 { "B" }
  else { "C" }
}

fn main() {
  print(grade(95))
  print(grade(80))
  print(grade(40))
}
```

<!-- output -->
```text
A
B
C
```

Without the last `else`, the whole `if` has no value when both conditions
are false. Its branches would be a string and nothing at all, which is what the error says.

## Recap

- Parameters and return types are written out; locals are inferred.
- `fn f(x: int) => x * 2` is a whole function.
- A missing return or a wrong argument type is a compile error.

In the reference: [Functions](https://tin.ad/docs/ref/language/#functions)
