detectivemittens

detectivemittens

Resources for Learning Recursion

On @AstonJ’s suggestion, I decided to start a thread on recursion. It’s one of my biggest mental hurdles to get over while learning FP. (My OOP brain just wants to iterate through everything.)

I’ve scoured the Internet for good resources on recursion, but I’ve come up empty. So far, I’ve seen suggestions of reading through The Little Schemer to really learn how to think recursively. I’m also doing the problems in Dave Thomas’s Programming Elixir, but I’m only able to wrap my head around the simpler problems.

Do you guys have any tips on how to think recursively?

Most Liked

NobbZ

NobbZ

For Elixir it is a little bit harder than other languages. But the first thing you need to realise is, that recursion is just the natural way to define loops in functional languages.

Also, for datatypes which are recursively defined (like a linked list or trees) its rather natural to follow the structure of the datatype also with the way of function calls.

Lets say we have a struct with the fields :value, :left, and :right. You might see from the pattern that this is meant to be a simple binary tree, so lets call it Tree for now. The field :value can hold arbitrary values and the other two fields do hold another Tree or nil.

So if we want to check if a certain value is in that tree, it is the easiest to just define it like the following:

def find(%Tree{value: v}, v), do: true
def find(%Tree{left: l, right: r}, v), do: find(l, v) || find(r, v)
def find(nil, _), do: false

Also you should never ever handle anything in the multi-headed function what is not expected from your definition of your datatype. I have to say, that this last paragraph is my personal opinion, but does line up well with what you get from the typing of other languages as well with “let it crash”-philosophy from Erlang and Elixir.

A much bigger problem, I have to admit, often it is, to rewrite a not tail recursive function into a tail recursive one, by splitting it into a public API-function and a private “worker” or “do” function which does carry one or more accumulating arguments around. This of course feels like some kind of dark magic when you try it for the first time, but as you go along, try hard and learn it will get easier and easier everytime you do it. Also your ability to recognise non-tail-recursive functions on the first glance will increase.

@bthach: The problem is, that in many imperativ languages, there is still this dogma around, that recursion is a bad thing per se and blows the stack. This was true until early 1990s, but since then more and more compilers got some optimisation technics called “tail call optimisation” which does rephrase tail-recursive-calls into some looping mechanism on the targeted (virtual) machine. So in imperative languages there are the same two kinds of recursion as we have in functional: “bad” and “good” recursion, but since functional languages relied on recursion from the very beginning, they’ve used it as provided. In the imperative languages, they do have “good” and “bad” as well, but they learned that recursion were always bad. And younger devs, comming straight from university who do know it better can’t win a fight against all that old seasoned devs in industry.

Maybe the situation is a little bit better in industries that use more modern technology than C or C++, but the above paragraph shows, what I have experienced in person and what I’ve heard by co-students in similar situations.

arkgil

arkgil

When writing recursive functions, first I try to think about stop condition, i.e. when I need to stop execution and return the result.

Also I try to think of all different states function’s argument might have, and which of them are relevant for my solution.
For each of these states I write another function head.

This is of course very basic and simple approach, although it might be enough for start:) Once you get used to recursion you will miss it in classic imperative languages :smiley:.

uranther

uranther

These online books on functional programming are good resources to learn FP concepts and recursion:

I hope that helps!

Where Next?

Popular in Questions Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement