# Blog post (beginner): Deriving Simple Recursive Functions

This one is aimed at beginners learning to write their first recursive functions. It describes a technique that I found useful, back when I taught Haskell to first-year students.

http://jackkelly.name/blog/archives/2023/01/08/deriving_simple_recursive_functions/

4 Likes

I also teach Haskell to first-years. In our case, students are very well grounded in the notion of proof by induction (especially proofs over the naturals). This makes the introduction of simple recursion much easier by analogy to induction.

The obvious example is the factorial function:

``````fac 0 = 1
fac n = n * (n-1)
``````

We can view this as a proof that \$n! = Î _{1â€¦n} n\$. The first line constitutes the base case, and the second line the inductive step. The same definition of factorial is already a well-known recurrence which anyone who has taken pre-calc (or Core maths at A-level in the UK) will recognise.

The same idea can be used for `product` by inducting over suffixes of the input.

Itâ€™s interesting to see your alternative take, thanks for sharing!

I think of it as an alternative presentation of the same idea of induction. â€śHey 2 * 3 * 4 * 5 looks like 2 * product [3, 4, 5]â€ť is exemplifiying the induction proof underneath.

While we are at it, shameless plug of how I do it. To be fair, my students are 2nd/3rd year and have seen even â€śprove this inequality containing unknown constants, during the proof discover good values for the constantsâ€ť, so it is a bit more believable that you can discover code during the proof too. To be fair^2, even 50yos fear recursion as much as total newbies do.

To be sure, I got from Graham Hutton, maybe also Ralf Hinze and Richard Bird etc., the idea of starting the proof first and letting the code emerge later.

On exams, I legit give hints like â€śNotice product [2, 3, 4, 5] = 2 * 3 * 4 * 5 = 2 * product [3, 4, 5] hint hint wink winkâ€ť, albeit for tougher questions than product.

1 Like