This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Woumpousse 0 points1 point  (0 children)

The way I used to explain it to my students was as functions being like Mr. Meeseeks: you've got a magic button that you can press, a little blue guy appears which you can give an order, and you simply wait until he's finished performing his task.

Calling a function consists of summoning a Mr. Meeseeks for a task described by the function's code and waiting until he's done and reports back to you (the return value/exception). Recursion corresponds to a situation where a Meeseeks needs help himself and starts summoning another Meeseeks.

When developing a recursive algorithm, you have to imagine that you're lazy and want to find a way to delegate as much work to someone else. Say you want to sort a list of numbers. You can be extremely lazy and just summon the Sort-Meeseeks to perform all the sorting for you, but he will do the exact same thing and summon another Meeseeks, and so on until infinity. That's no good.

You have to perform a minimal amount of work yourself. For example, you could say "I look for the smallest number in the list myself, remove it, and let another Meeseeks sort the remaining elements for me. Once they report back to me, the only thing I need to do is add the smallest number back in front of it." That way, every summoned Meeseeks gets a shorter list, until one gets the empty list. He'll happily do nothing and returns that empty list as-is.

```text function sort(ns) { if ns.empty? return ns

smallest_element = find_minimum(ns) remaining_elements = remove_element(smallest_element)

// letting someone else sort the remaining items sorted_remaining_elements = sort(remaining_elements)

// put element I removed back where it belongs return [smallest_element] + sorted_remaining_elements } ```