<p>It seems that no language supports this feature:</p>
<blockquote>
<p>Define a function that can return the function itself.</p>
<p>This function will continue to be called and continue to return itself.</p>
</blockquote>
<p>For example:</p>
<pre class="lang-typescript prettyprint-override"><code>function fmt(value: bool|integer|string): fmt {
    print(value)
    self
}

let f = fmt(false)(0)(&quot;string&quot;)
f([]) // unexpected argument type `Array`
</code></pre>
<p>I refer to statically typed and type-safe functions, excluding <code>type erasured function</code>, <code>function pointers</code>, etc.</p>
<hr />
<p>My question is:</p>
<blockquote>
<p>Why don't languages support this kind of function definition?</p>
</blockquote>
<p>If it is because the right side of the function must be a defined type, then in fact many languages support this operation when defining a class:</p>
<pre class="lang-typescript prettyprint-override"><code>class BinaryTree {
    lhs: BinaryTree?
    rhs: BinaryTree?
}
</code></pre>

<syntax><functions>
How about support function return itself?
CC BY-SA 4.0
2023-12-19T14:14:30.637Z
This doesn't seem worth the added complexity to me. Your particular example could be 3 separate function calls anyway. Chaining methods is quite common (e.g., builders in Java and Rust) but it doesn't require special language features and wouldn't be covered by what you're proposing anyway
user
CC BY-SA 4.0
2023-12-19T15:07:21.157Z
If I get the spirit of your question correctly, the answer would be that you would need some sort of fixed point to type the function. I guess that there are languages that have it in the research field, but it has no practical use because most people won't be able to understand what's going on. OOP is also a solution but I guess you won't count it here.
feldentm
CC BY-SA 4.0
2023-12-19T16:14:53.783Z
You can in my language, and in Lua too IIRC
Seggan
CC BY-SA 4.0
2023-12-19T16:54:42.640Z
In a statically typed language, what would be the type of such a function?
Christian Lindig
CC BY-SA 4.0
2023-12-19T17:14:08.697Z
@ChristianLindig If we take `Fix` to be the operator for constructing (equi-)recursive types and `Λ` to be a type-level lambda, then it could have the type `Fix (Λ r. (bool|integer|string) -> r)`
David Young
CC BY-SA 4.0
2023-12-19T18:23:52.693Z
Can you give an example of a language with first-class functions (i.e. where it is possible to return functions at all) in which a function specifically cannot return *itself*? I don't know if this is really true of any languages, except perhaps if they have a static type system which doesn't have a way to express the type of a function which returns itself. In most cases you would be able to express a type like `Supplier<Object>` (e.g. in Java) to get around the fact that you can't write an infinitely nested `Supplier<Supplier<Supplier<...>>>` type.
kaya3
CC BY-SA 4.0
2023-12-19T18:46:03.703Z
It is not clear whether you are referring to functions that return a call to the function itself (recursive) or a function that returns the actual function itself.
CPlus
CC BY-SA 4.0
2023-12-19T22:08:38.213Z
@kaya3 That's specifically the problem. They wrote: **I refer to statically typed and type-safe functions**
Barmar
CC BY-SA 4.0
2023-12-19T22:14:28.207Z
@Barmar There is nothing type-unsafe about `Supplier<Object>`; it's just not very specific. And if that is the question, then it should not be about supporting functions which return themselves, it should be explicitly about function *types*.
kaya3
CC BY-SA 4.0
2023-12-19T22:16:13.733Z
Even then, the claim that no languages support this ─ even if the claim is just about having a maximally specific return type in a statically typed language ─ is still wrong. Here's [Typescript](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcAUBKAXIqBPABwFM5hlVEBvAKEUQCcioR6kU4BuagX2qA) for example.
kaya3
<p>Let me reverse the question:</p>
<blockquote>
<p>Why <em>would</em> a language support that kind of function definition?</p>
</blockquote>
<p>Recursive data structures are very useful. Self-returning functions, on the other hand, don't add anything.</p>
<ol>
<li>You can't implement recursive data structures with simple term rewriting, but you could &quot;support&quot; self-returning functions with simple manual substitutions or even macros (roughly <code>fmt(&lt;arg1&gt;)(&lt;arg2&gt;)</code> → <code>fmt(&lt;arg1&gt;); fmt(&lt;arg2&gt;)</code>, repeatedly applied).</li>
<li>Returning a type alias would also be an option. (Like <code>type fmt_func = (bool|string|integer -&gt; fmt_func)</code> and then having <code>function fmt(value: bool|integer|string): fmt_func</code>.) It's a broader type than functions returning themselves, but also far more useful -- think state machines, for example.</li>
<li>Why would you want to have it anyway? Language features have to justify their existence, most people designing languages don't think &quot;why not?&quot; is sufficient justification.</li>
</ol>

CC BY-SA 4.0
2023-12-19T15:15:18.603Z
2023-12-19T15:15:18.603Z
Jasmijn
<p>Julia supports this (and in fact compiles it efficiently with no dynamic behavior)</p>
<pre><code>julia&gt; f() = return f
f (generic function with 1 method)

julia&gt; f()
f (generic function with 1 method)

julia&gt; f()()()
f (generic function with 1 method)

using BenchmarkTools

julia&gt; @btime f()
  0.863 ns (0 allocations: 0 bytes)

julia&gt; @code_native debuginfo=:none f()
    .text
    .file   &quot;f&quot;
    .globl  julia_f_80                      # -- Begin function julia_f_80
    .p2align    4, 0x90
    .type   julia_f_80,@function
julia_f_80:                             # @julia_f_80
    .cfi_startproc
# %bb.0:                                # %top
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register %rbp
    popq    %rbp
    .cfi_def_cfa %rsp, 8
    retq
.Lfunc_end0:
    .size   julia_f_80, .Lfunc_end0-julia_f_80
    .cfi_endproc
                                        # -- End function
    .section    &quot;.note.GNU-stack&quot;,&quot;&quot;,@progbits

<span class="math-container">```</span>
</code></pre>

CC BY-SA 4.0
2023-12-19T16:03:34.843Z
2023-12-19T16:03:34.843Z
Oscar Smith
<p>Counterpoint to the question:</p>
<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; def a():
...     print('a')
...     return a
... 
&gt;&gt;&gt; a()()()()()()()()
a
a
a
a
a
a
a
a
&lt;function a at 0x7f14b611fce0&gt;
&gt;&gt;&gt; 
</code></pre>
<p>Python 3 does in fact support it. Probably as a result of <code>a</code> only being resolved at runtime.</p>

CC BY-SA 4.0
2023-12-19T15:58:43.043Z
2023-12-19T15:58:43.043Z
kouta-kun
CC BY-SA 4.0
2023-12-19T18:59:27.887Z
..."statically typed and type-safe"...
feldentm
CC BY-SA 4.0
2023-12-20T17:03:50.353Z
You can do `T = typing.Callable[[], T]` then `def a () -> T` to make it type safe
mousetail 'he-him'
CC BY-SA 4.0
2023-12-20T19:59:50.143Z
@mousetail type-safe-ish, considering Python itself will just ignore that if you don't use MyPy or some other extension.
kouta-kun
CC BY-SA 4.0
2023-12-20T20:06:54.490Z
@kouta-kun I feel the distincion is kind of meaningless, many "type safe" languages also let you ignore type errors if you don't configure things correctly, especially with function pointers. How it's checked is not really as relevant for safety as soundness.
mousetail 'he-him'
CC BY-SA 4.0
2023-12-23T08:06:44.133Z
The correct static type of this construct is `type RC[**P] = Callable[P, RC[P]]`, and for `a` it is `RC[[]]`. See [the MyPy playground](https://mypy-play.net/?mypy=latest&python=3.12&flags=show-error-context%2Cstrict%2Cdisallow-any-decorated%2Cdisallow-any-expr%2Cdisallow-any-explicit%2Cdisallow-any-generics%2Cdisallow-any-unimported%2Cdisallow-incomplete-defs%2Cdisallow-subclassing-any%2Cdisallow-untyped-calls%2Cdisallow-untyped-decorators%2Cdisallow-untyped-defs&gist=09e20728dc79fd013a2d0797cc9b8e4e) and Pylance agrees (using old style type declarations as new syntax is not supported yet).
MisterMiyagi
# How about support function return itself?
Posted by: username_0 on 2023-12-19
It seems that no language supports this feature:

Define a function that can return the function itself.
This function will continue to be called and continue to return itself.

For example:
function fmt(value: bool|integer|string): fmt {
    print(value)
    self
}

let f = fmt(false)(0)("string")
f([]) // unexpected argument type `Array`

I refer to statically typed and type-safe functions, excluding type erasured function, function pointers, etc.

My question is:

Why don't languages support this kind of function definition?

If it is because the right side of the function must be a defined type, then in fact many languages support this operation when defining a class:
class BinaryTree {
    lhs: BinaryTree?
    rhs: BinaryTree?
}
**Tags:** syntax functions
> **Comments:**
> **username_1**: This doesn't seem worth the added complexity to me. Your particular example could be 3 separate function calls anyway. Chaining methods is quite common (e.g., builders in Java and Rust) but it doesn't require special language features and wouldn't be covered by what you're proposing anyway  
> **username_2**: If I get the spirit of your question correctly, the answer would be that you would need some sort of fixed point to type the function. I guess that there are languages that have it in the research field, but it has no practical use because most people won't be able to understand what's going on. OOP is also a solution but I guess you won't count it here.  
> **username_3**: You can in my language, and in Lua too IIRC  
> **username_4**: In a statically typed language, what would be the type of such a function?  
> **username_5**: @ChristianLindig If we take `Fix` to be the operator for constructing (equi-)recursive types and `Λ` to be a type-level lambda, then it could have the type `Fix (Λ r. (bool|integer|string) -> r)`  
> **username_6**: Can you give an example of a language with first-class functions (i.e. where it is possible to return functions at all) in which a function specifically cannot return *itself*? I don't know if this is really true of any languages, except perhaps if they have a static type system which doesn't have a way to express the type of a function which returns itself. In most cases you would be able to express a type like `Supplier<Object>` (e.g. in Java) to get around the fact that you can't write an infinitely nested `Supplier<Supplier<Supplier<...>>>` type.  
> **username_7**: It is not clear whether you are referring to functions that return a call to the function itself (recursive) or a function that returns the actual function itself.  
> **username_8**: @kaya3 That's specifically the problem. They wrote: **I refer to statically typed and type-safe functions**  
> **username_6**: @Barmar There is nothing type-unsafe about `Supplier<Object>`; it's just not very specific. And if that is the question, then it should not be about supporting functions which return themselves, it should be explicitly about function *types*.  
> **username_6**: Even then, the claim that no languages support this ─ even if the claim is just about having a maximally specific return type in a statically typed language ─ is still wrong. Here's [Typescript](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcAUBKAXIqBPABwFM5hlVEBvAKEUQCcioR6kU4BuagX2qA) for example.  
---
## 3 answers
### Answer by username_9 on 2023-12-19. Score: 2
Let me reverse the question:

> Why *would* a language support that kind of function definition?

Recursive data structures are very useful. Self-returning functions, on the other hand, don't add anything.

1. You can't implement recursive data structures with simple term rewriting, but you could "support" self-returning functions with simple manual substitutions or even macros (roughly `fmt()()` → `fmt(); fmt()`, repeatedly applied).
2. Returning a type alias would also be an option. (Like `type fmt_func = (bool|string|integer -> fmt_func)` and then having `function fmt(value: bool|integer|string): fmt_func`.) It's a broader type than functions returning themselves, but also far more useful -- think state machines, for example.
3. Why would you want to have it anyway? Language features have to justify their existence, most people designing languages don't think "why not?" is sufficient justification.
---
### Answer by username_10 on 2023-12-19. Score: 1
Julia supports this (and in fact compiles it efficiently with no dynamic behavior)
julia> f() = return f
f (generic function with 1 method)

julia> f()
f (generic function with 1 method)

julia> f()()()
f (generic function with 1 method)

using BenchmarkTools

julia> @btime f()
  0.863 ns (0 allocations: 0 bytes)

julia> @code_native debuginfo=:none f()
    .text
    .file   "f"
    .globl  julia_f_80                      # -- Begin function julia_f_80
    .p2align    4, 0x90
    .type   julia_f_80,@function
julia_f_80:                             # @julia_f_80
    .cfi_startproc
# %bb.0:                                # %top
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register %rbp
    popq    %rbp
    .cfi_def_cfa %rsp, 8
    retq
.Lfunc_end0:
    .size   julia_f_80, .Lfunc_end0-julia_f_80
    .cfi_endproc
                                        # -- End function
    .section    ".note.GNU-stack","",@progbits

```
---
### Answer by username_11 on 2023-12-19. Score: 0
Counterpoint to the question:
>>> def a():
...     print('a')
...     return a
... 
>>> a()()()()()()()()
a
a
a
a
a
a
a
a

>>> 

Python 3 does in fact support it. Probably as a result of a only being resolved at runtime.
> **Comments:**
> **username_2** (2023-12-19): ..."statically typed and type-safe"...  
> **username_12** (2023-12-20): You can do `T = typing.Callable[[], T]` then `def a () -> T` to make it type safe  
> **username_11** (2023-12-20): @mousetail type-safe-ish, considering Python itself will just ignore that if you don't use MyPy or some other extension.  
> **username_12** (2023-12-20): @kouta-kun I feel the distincion is kind of meaningless, many "type safe" languages also let you ignore type errors if you don't configure things correctly, especially with function pointers. How it's checked is not really as relevant for safety as soundness.  
> **username_13** (2023-12-23): The correct static type of this construct is `type RC[**P] = Callable[P, RC[P]]`, and for `a` it is `RC[[]]`. See [the MyPy playground](https://mypy-play.net/?mypy=latest&python=3.12&flags=show-error-context%2Cstrict%2Cdisallow-any-decorated%2Cdisallow-any-expr%2Cdisallow-any-explicit%2Cdisallow-any-generics%2Cdisallow-any-unimported%2Cdisallow-incomplete-defs%2Cdisallow-subclassing-any%2Cdisallow-untyped-calls%2Cdisallow-untyped-decorators%2Cdisallow-untyped-defs&gist=09e20728dc79fd013a2d0797cc9b8e4e) and Pylance agrees (using old style type declarations as new syntax is not supported yet).  
---
