In writing recursive functions (functional style), I often need to refer to the current function (depending on the context). e.g.
f 0 = 0
f (S n) = f n + 2
Are there any functional languages that allow using a generic name such as this_function
or self
to be used instead of the specific function name f
?
So, hypothetically, the above would be rewritten as
f 0 = 0
f (S n) = self n + 2
It seems to make the spot of recursion easier to identify and the intention clearer. Also, it seems to allow one to write recursive anonymous functions, e.g. a function to double a number in pseudo-code:
\n r -> if n > 0 then self (n - 1) (r + 2) else r
Does such facility exist or is it possible?
append
, I make a call toappend
because I've done some of the work and now I need to append two lists. The fact that it happens to be the same function is almost a coincidence. If it were a different fn that also appended it'd still work. I just need to ensure I make progress. This is often how I think about recursion: "do some of the work, then treat the function 'as though it already works' when making recursive calls" $\endgroup$\n r -> ...
can best be understood as syntactic sugar for\n -> \r -> ...
. But your example,\n r -> ... self (n-1) (r+2) ...
relies critically on\n r -> ...
and\n -> \r -> ...
having distinct meanings. Or considerf x = if x > 0 then (\n -> ...self...) else (\n -> 3)
; here you must decide whetherself
should refer to just the inner\n -> ...
or to the entiref x = ...
. Of course all of these decisions can be made, it just may be more complicated than you first think. $\endgroup$f
has code that includes the symbolf
itself. The goal is to make this recursive call without relying on the name. So, for example, it should be possible to rename the function and still have it work and make those recursive calls, without changing the code inside. $\endgroup$