# How do you write a fun that's recursive in Erlang?

I'm trying to write a recursive fun in an Erlang shell, but I keep getting an unbound variable exception:

`1> Foo = fun(X) -> Foo(X) end. * 1: variable 'Foo' is unbound `

This probably goes without saying, but I'm not trying to create an infinite loop! This is just a simple example of the error I'm getting.

You can do it with a little argument trick:

```1> Foo = fun(F, X) -> F(F, X) end. #Fun<erl_eval.12.113037538> 2> Foo(Foo, a). <...infinite loop!> ```

The trick here is to send in the function as an argument to itself to allow recursion.

Alternative way to make it in one shoot:

```1> Foo = fun(X) -> Fun = fun(F,Y) -> F(F,Y) end, Fun(Fun,X) end. #Fun<erl_eval.6.13229925> 2> Foo(a). ```

For example:

```1> Foo = fun(Max) -> 1> Fun = fun(F, X) when X > Max -> []; 1> (F, X) -> [X | F(F, X+1)] 1> end, 1> Fun(Fun, 0) 1> end. #Fun<erl_eval.6.13229925> 2> Foo(10). [0,1,2,3,4,5,6,7,8,9,10] ```

Alternatively, you can use the Y combinator. Y Combinator in Erlang explains.

You can also use the "Funs with names" variant:

```Foo = fun F(X) -> F(X) end. ```

In this way it is easier to understand that `F` is the function itself within the definition. Also, `Foo` and `F` can be the same variable.

Obviously, Foo gets assigned only after the fun is defined, so it may not be accessed from within it.

I don't think that Erlang allows to call the anonymous function from itself. Just make it a named one.

Category:recursion Views:0 Time:2009-05-15

## Related post

• How to calculate Big O notation from piece of code 2008-08-06

Most people with a degree in CS will certainly know what Big O stands for. It helps us to measure how (in)efficient an algorithm really is and if you know in what category the problem you are trying to solve lays in you can figure out if it is still

• Why should I learn Lisp? 2008-08-07

I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it. I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it i

• Learning Regular Expressions 2008-08-07

I don't really understand regular expressions. Can you explain them to me in an easy-to-follow manner? If there are any online tools or books, could you also link to them? --------------Solutions------------- The most important part is the concepts.

• How to add CVS directories recursively 2008-08-07

I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running "cvs add" only adds the contents of the current d

• How do you persist a tree structure to a database table with auto incrementing IDs using an ADO.NET DataSet and a DataAdapter 2008-08-07

I have a self-referential Role table that represents a tree structure ID [INT] AUTO INCREMENT Name [VARCHAR] ParentID [INT] I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of

• Better windows command line shells 2008-08-08

Is there a better windows command line shell other than cmd which has better copy paste between Windows' windows and console windows? --------------Solutions------------- Take Command does support Copy/Cut/Paste from the keyboard and the mouse. It's

• Best way to abstract season/show/episode data 2008-08-08

Basically, I've written an API to www.thetvdb.com in Python. The current code can be found here. It grabs data from the API as requested, and has to store the data somehow, and make it available by doing: print tvdbinstance[1][23]['episodename'] # ge

• Date arithmetic in Unix shell scripts 2008-08-08

I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. I'm using a function to increment a day and another to decrement: IncrementaDia(){echo \$1 | awk 'BEGIN { diasDelMes[1] = 31 diasDelMes[2]

• Scaling multithreaded applications on multicored machines 2008-08-09

I'm working on a project were we need more performance. Over time we've continued to evolve the design to work more in parallel(both threaded and distributed). Then latest step has been to move part of it onto a new machine with 16 cores. I'm finding

• Is there a way to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field? 2008-08-09

To illustrate, assume that I have two tables as follows: VehicleID Name 1 Chuck 2 Larry LocationID VehicleID City 1 1 New York 2 1 Seattle 3 1 Vancouver 4 2 Los Angeles 5 2 Houston I want to write a query to return the following results: VehicleID Na

• Of Ways to Count the Limitless Primes 2008-08-10

Alright, so maybe I shouldn't have shrunk this question sooo much... I have seen the post on the most efficient way to find the first 10000 primes. I'm looking for all possible ways. The goal is to have a one stop shop for primality tests. Any and al

• Is it "bad practice" to be sensitive to linebreaks in XML documents? 2008-08-10

I'm generating some XML documents and when it comes to the address part I have fragments that look like this: <Address>15 Sample St Example Bay Some Country</Address> The XSLT that I have for converting this to XHTML has some funky recurs

• What is Turing Complete? 2008-08-10

What does the expression "Turing Complete" mean? Can you give a simple explanation, without going into too many theoretical details? --------------Solutions------------- Here's the briefest explanation: A Turing Complete system means a system in whic

• Merge Sort a Linked List 2008-08-11

I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here. --------------Solutions------------- Wonder why it should be big challenge a

• How do you get the icons out of shell32.dll? 2008-08-12

I'd like to get the Tree icon to use for a homegrown app. Does anyone know how to extract the images out as .icon files? I'd like both the 16x16 and 32x32, or I'd just do a screen capture. --------------Solutions------------- This should get you star

• Best way to access a control on another form in Windows Forms? 2008-08-12

First off, this is a question about a desktop application using Windows Forms, not an ASP.NET question. I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following... otherForm.Controls["na

• Keep Remote Directory Up-to-date 2008-08-12

I absolutely love the Keep Remote Directory Up-to-date feature in Winscp. Unfortunately, I can't find anything as simple to use in OS X or Linux. I know the same thing can theoretically be accomplished using changedfiles or rsync, but I've always fou

• Best tool for auto-generating SQL change scripts for SQL Server 2008-08-14

I'm doing a survey for the best SQL change script generators out there, specifically for MS SQL Server. I do know of Redgate SQL Compare, but I'd like to know what others use, and if there are free versions of such software that I could try. Any sugg

• SQL, Auxiliary table of numbers 2008-08-14

For certain types of sql queries, an auxiliary table of numbers can be very useful. It may be created as a table with as many rows as you need for a particular task or as a user defined function that returns the number of rows required in each query.

• Best way to model Many-To-One Relationships in NHibernate When Dealing With a Legacy DB? 2008-08-14

Warning - I am very new to NHibernate. I know this question seems simple - and I'm sure there's a simple answer, but I've been spinning my wheels for some time on this one. I am dealing with a legacy db which really can't be altered structurally. I h