Write your own function

Parameters, a result type Lean holds you to, and checks that call your code.

14 minBeginnerdefparametersresult type
0/11 completed in this course

Until now the definitions were given. Here is how to write one, with its parts labelled:

--  name    parameters     result   body
def area    (w h : Nat)  : Nat   := w * h

#eval area 3 4
Lean replies
12

Parameters go in brackets with their type. Two parameters of the same type can share brackets: (w h : Nat) means the same as (w : Nat) (h : Nat).

The result type is a promise, and Lean holds you to it. A body of the wrong type is rejected right at the definition:

Lean rejects this
def label (n : Nat) : String := n
Lean replies with an error
Type mismatch

Under your answer are read-only checks that call your functions. They must compile, so your names, parameter types and results have to match what they expect.

Worked example

def area (w h : Nat) : Nat := w * h

def greet (name : String) : String := "Hello, " ++ name

#eval area 3 4
#eval greet "Ada"

Your exercise has two definitions as well: one on numbers and one on text.

Takeaway

A definition has a name, typed parameters, a result type and a body. Lean checks the body against the result type.

Practise on Problems
Exercise 1 of 3

Write triple, which multiplies a natural number by three, and shout, which adds ! to the end of a string.

Suggested steps
  1. Define triple, from a Nat to a Nat
  2. Define shout, from a String to a String

These marks only recognize text. Another correct proof may use different steps; Lean checks whether it works.

Exercise.lean
Loading editor…

These lines run underneath whatever you write. They are what decides the exercise, so your names and types have to match them.

-- These run under your definitions and have to compile.
example : triple 4 = 12 := by rfl
example : triple 0 = 0 := by rfl
example : shout "go" = "go!" := by rfl
example : shout "" = "!" := by rfl
ReadyLn 1, Col 1Lean 4
Draft saved in this browser
Stuck?
Recall and apply

Knowledge check

Answer without looking back, then check your reasoning.

0of 3
correct
Question 1 of 3What does the result type in a def do?
Question 2 of 3What does def area (w h : Nat) : Nat declare?
Question 3 of 3Why must your names match the checks under the editor?