# Arbitrary-length currying

Write a function, f, that takes in a positive integer and returns a function.

The new function returned should be identical to f. However, when the "termination call" happens, f should instead return the sum of all integers passed.

For example, g=f(4) (if f is the first function) should set g to another function. h=g(3) will do the same. However, when you call h with no arguments (see below for details), it should output 7, as that is the sum of the previous function arguments. Put another way, f(3)(4)() == 7.

Do note this is not the same as f(3,4)().

"Termination call" is one of the following options (your choice):

• call w/o arguments
• null as argument
• any non-positive value

Arbitrary amount of function calls should be supported, there is no predefined limit.

It's guaranteed that total sum will not be bigger than 1'000.

We can assume that there is at least one call is made prior to "termination call".

Your code should not use static, per-program variables, so it should be possible to run the experiment multiple times in the same runtime and observe exactly the same behavior.

Examples:

f(1)() == 1
f(4)(2)(7)() == 13
f(4)(2)(7)(5)(2)() == 20

• @LuisMendo It generally means that f(4) returns a new function. If that new function is called without arguments, it returns 4, but if it's called with another argument then it will again return a new function with the same semantics but with the new argument added to the 4 and so on. Commented Apr 19, 2017 at 21:42
• @LuisMendo It's indeed up to Eugene, but I think that allowing repeated calls would significantly take away from the challenge, because the interesting part isn't to make a stateful function but to make a higher-order function. Commented Apr 19, 2017 at 21:49
• @MartinEnder That makes a lot of sense. Eugene, if that's the intent, please change the wording of the challenge. Write a function that can be infinitely called doesn't suggest at all that the function shoud return a function Commented Apr 19, 2017 at 21:58
• Can we assume that there will only be one instance of the call chain at a time? E.g. No q = f(2)(3); b = f(1)(2)(3); q(); b()? Commented Apr 19, 2017 at 22:08
• Having just recently picked up Haskell, I'm interested in whether this is possible in Haskell. The strong type system makes me think it might not be. Commented Apr 20, 2017 at 7:06

## JavaScript (ES6), 18 bytes

f=n=>m=>m?f(m+n):n


Pass a falsy value to retrieve the sum. Zeros could be allowed for a cost of 2 bytes.

Try it online

Ungolfed:

f = function(n) {
return function(m) {
if (m) {
return f(m+n);
} else {
return n;
}
}
}

• Brilliant submission! Commented Apr 19, 2017 at 19:21

This is 98 bytes for the code and 20 bytes for the GHC compiler flag -XFlexibleInstances, which enables a type system extension.

class F a where f::Int->a
instance F(()->Int)where f n()=n
instance F a=>F(Int->a)where f=(f.).(+)


This defines a "function" f, which can be called with an arbitrary number of integers followed by the unit (), after which it returns an integer. Type annotations are required. Try it online!

## Explanation

Forcing Haskell's strict type system to allow this requires some magic, namely, enabling the GHC extension for flexible typeclass instances. How this works is that f is a parametrically polymorphic function restricted by a type class constraint: its type is F a => Int -> a. This means that f takes an integer and returns a value of type a, for any type a that belongs to the typeclass F. F is just the name of the typeclass that provides the function f; it's declared on the first line.

The next two lines are two instances of F for different types a. The second line states that the type of functions from () to integers belongs to F (where () is the unit type whose only member is the value ()), and the implementation is f n () = n; the function returns its first argument. The last line states that if a belongs to F, then so does the type of functions from integers to a: from a function f :: Int -> a we can generate another function f :: Int -> Int -> a. The implementation is f m n = f (m+n) (the code uses combinators to make it shorter), where the f on the left is the new one, and the f on the right is the old one. This essentially gives f a new integer argument, which is added to the next one. Multiple arguments are summed together like this:

  f  a1   a2   a3   a4   a5  ()
= f (a1 + a2)  a3   a4   a5  ()
= f (a1 + a2 + a3)  a4   a5  ()
= f (a1 + a2 + a3 + a4)  a5  ()
= f (a1 + a2 + a3 + a4 + a5) ()
=    a1 + a2 + a3 + a4 + a5


The f on each line has a different type.

Haskell functions are curried automatically, so if you give f only integers, you get a function.

• Maybe I'm nitpicking, but it's not quite what the challenge asks for. You're defining two(!) functions, both called f, not a single function that does the job. However, this is as close as you can get in Haskell. I don't think it's possible to solve the task with a single function because of the strict type system.
– nimi
Commented Apr 20, 2017 at 20:45
• @nimi This defines not two functions called f, but infinitely many functions called f. (One for each possible number of arguments.) These functions (from this infinite family) have two sorts of definitions, one sort when the number of arguments is zero, and another when it is not. Commented Apr 21, 2017 at 4:44
• @ShreevatsaR: I see two definitions, f n()=n and f=(f.).(+), so I'd call it defining two functions.
– nimi
Commented Apr 21, 2017 at 5:27
• @nimi There are two definitions, but not two functions. The number of definitions need not be the number of functions. For example, you can define the factorial function with the two definitions g 0 = 1 and g n = g (n-1) * n, where there are two definitions but just one function. Here we have two definitions but infinitely many functions. (Each of a different type.) Commented Apr 21, 2017 at 5:53
• @nimi BTW in ghci load the above and try :t f— it will say f :: F a => Int -> a (meaning that if a is an instance of class f, then f is a function Int -> a). So we could consider this as either one function or infinitely many, but although it has two sorts of definitions (just like the factorial function) I don't see any good basis for considering it to be two functions. Commented Apr 21, 2017 at 18:34

# Python 2, 4241 36 bytes

This solution will never have an overflow, since Python supports arbitrary-precision integers. Zero is the "special value".

f=lambda n:lambda m:m and f(m+n)or n


Try it online

Ungolfed:

def f(n):
def g(m=''):
return f(m+n)if m<''else n
return g


## Mathematica, 25 bytes

f[x_]@y_=f[x+y]
f[x_][]=x


Try it online! (Using Mathics.)

It's possible to do three bytes less by porting the JavaScript answer, but I wanted to present a more idiomatic Mathematica solution. The @ is just a bit of syntactic sugar, which makes the solution equivalent to:

f[x_][y_]=f[x+y]
f[x_][]=x


So yeah the idea is that in Mathematica you can't just define a function f[x_] but you can directly attach a value to a more complicated expression containing f, e.g. f[x_] being passed another argument. By setting up two definitions for this, we can get the desired behaviour:

• The first definition collapses one f[x][y] call into f[x+y], thereby consuming one "call" and adding up the arguments inside. This rule applies until we're left with f[sum][].
• The second definition unpacks this final case by defining the entire thing to evaluate to sum.
• <3 symbolic programming Commented Apr 19, 2017 at 23:41

# C, 62 58 bytes, borderline competing

Saved 4 bytes thanks to Kevin! (Still not removing typedef because it's something needed in order to be called.)

typedef(*(*B)(_))(_);q;f(x,o,_){x=x?(q+=x,f):(x=q,q=0,x);}


The function to call is f; you stop calling it and get the result by calling it with a non-positive number like 0. Try a test harness online!

So, as far as I can tell, the only way to "curry" functions that have multiple return types is to do one of the following:

1. Cast the result to a function to tell the compiler you wish to call the result again;
2. or create a union/struct type that has an int and function/self-referential subtypes.

I tried doing (2), but it seemed a bit against the spirit of the question and, quite frankly, nigh undoable. Thus, in keeping with the spirit of the challenge, I have opted for option (1). This requires casting each returned function into a function, that it may be used.

This "currying" syntax looks a bit odd, but is quite similar. To emulate f(21)(1), one would have to write ((B)((B)f(21))(1))(0). I defined the B type to be a function that takes an integer and returns a pointer to a function that takes an integer. Expanded, this looks like:

   ( (B)( (B) f(21) )(1) )(0)
//            f(21)            - call f with 21
//        (B)                  - cast to B, a function pointer
//      (           )(1)       - call with 1
//   (B)                       - cast to a function pointer
// (                     )(0)  - call with 0

• If you say it terminates on 0 only, you're going to require the casting (which you do in C because C can't properly define a function that returns itself), and you leave clearing the global between runs to the caller (which I think is perfectly reasonable), you can simplify the entire thing to q;f(x){return x?(q+=x,f):q;}. Commented Apr 20, 2017 at 6:48
• Try it online! Commented Apr 20, 2017 at 6:48
• @Kevin yet, as per site rules, a function must be reusable. If I didn't zero q after each run, then the function would no longer be useable Commented Apr 20, 2017 at 11:14
• Maybe function pointers? You'd have to de reference every time but might be worth checking out Commented Apr 20, 2017 at 14:04
• @ConorO'Brien I just implemented your union approach. It's longer than this one, but it's not far off. Commented May 24, 2018 at 20:00

# C++, 72 bytes

#define O(P)operator()(P){return{P+a};}int
struct F{F O(int(m))O()a;}f;


This defines a type F which acts as the requested function, and a variable f of that type to invoke. It's valid as of C++11 and works with online versions of GCC, clang, icc and VC++.

Usage:

int main() {
return f(1)(2)(3)(); // returns 6
}


Explanation:

After preprocessing and reformatting, it looks like:

struct F {
F operator()(int(m)) { return{int(m)+a}; }
int operator()() { return {+a}; }
int a;
} f;


This would normally be written:

struct F {
F operator()(int m) { return {m+a}; }
int operator()() { return a; }
int a;
} f;


return a; and return {+a}; do the same thing, as unary + doesn't change the value, and redundant braces around the return value are allowed. int m and int(m) do the same thing, as redundant parentheses around a variable name are allowed, including function parameters. return {m+a}; and return {int(m)+a}; do the same thing, as a cast of m from int to int does not change its value. These changes get the two operator() overloads closer in syntax, allowing a single macro definition to be invoked twice. Picking the right order for the three members allows the first word of the next line (int) to be included in the macro definition as well.

• Beautiful. And not just the golfed solution...overloading operator() to make this work was especially cool. Commented Nov 2, 2017 at 3:10

# Ruby, 23 bytes

f=->n{->m{m ?f[n+m]:n}}


Usage:

f[1][2][3][nil]
=> 6


# C, 104 96 bytes

#define a(i)s(i)|b
#define b(i)u(i)|c
#define c(i)u(i)|b
b,c,d;s(i){b=c=i;i=d;}u(i){c=b+=i;i=d;}


Uses the method from the link that @JulianWolf shared. Last argument must be 0.

Try it online!

• Comments are not for extended discussion; this conversation has been moved to chat. Commented Apr 20, 2017 at 18:54

# Math.JS, 38 Bytes

f(x)=i(x,0)
i(x,y)=x<0?y:j(z)=i(z,y+x)


Call it with f(number_a)(number_b)(...)(negative_number)

If we're allowed to specify the initial call, 12 bytes (f(x)=i(x,0)\n) can be dropped, and it can be called with i(number_one,0)(number_two)(...)(negative_number)

Try it!

## Explanation

\begin{align} f(x) & = i(x, 0) \\ i(x, y) & = \begin{cases} y, & \text{if } x < 0 \\ j(z) = i(z, y+x), & \text{otherwise} \end{cases} \end{align}

As shown above, f(x) simply calls i(x,0), then, i(x,y) returns the value of y if x is less than 0, or the function j(z)=i(z,x+y) otherwise.

## C, 232 206 bytes

#include<string.h>
#include<stdlib.h>
#define f(X)s(""#X)?0:g
#define g(X)u(""#X)?0:h
#define h(X)u(""#X)?0:g
g=0,h=0;s(char*s){g=h=atoi(s);return 0;}u(char*s){char*a=strlen(s)?s:"0";g=h+=atoi(a);return 0;}


This can probably be golfed significantly, but should serve as a proof of concept that C can be used, without any language extensions*, to solve this problem by calling without arguments rather than with a magic value.

* @hvd has noted that, while this works out of the box using gcc, some of the behavior is not defined in the C standard, meaning that this may not be portable. Use at your own risk!

Ungolfed:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define f(X) start("" #X) ? 0 : f0
#define f0(X) update("" #X) ? 0 : f1
#define f1(X) update("" #X) ? 0 : f0

long f0 = 0;
long f1 = 0;

int start(const char *s) {
f0 = f1 = strtol(s, NULL, 10);

return 0;
}

int update(const char *s) {
const char *a = strlen(s) ? s : "0";
f0 = f1 += strtol(a, NULL, 10);

return 0;
}

int main() {
printf("f(1)()          -> %ld\n", f(1)());
printf("f(1)(2)(0)(3)() -> %ld\n", f(1)(2)(0)(3)());
printf("f(1)(-2)(3)()   -> %ld\n", f(1)(-2)(3)());
printf("f()             -> %ld\n", f());

return 0;
}


Compiling and running with gcc arbitrary-length-currying.c -o arbitrary-length-currying && ./arbitrary-length-currying outputs (after some warnings)

f(1)()          -> 1
f(1)(2)(3)(0)() -> 6
f(1)(-2)(3)()   -> 2
f()             -> 0

• "without any language extensions" -- The trick of alternating between g and h to continue a chain of macro invocations is not guaranteed to work, as it's unspecified whether the next g appears in the context of the expansion of the first g. C11 adds an example to 6.10.3.4 to spell out that it's unspecified. (IIRC, TenDRA's preprocessor is one that wouldn't expand it the way you want.) Aside from that, no version of the language supports both empty macro arguments and implicit int, so a valid C program cannot use both. :) Still, nice answer. Are you looking to golf it further?
– hvd
Commented Apr 22, 2017 at 14:18
• @hvd: yeah, probably gonna come back to it in a couple of days and see if I can golf it down. You're definitely right that this is unspecified behavior, but I think the standard treatment on here is that languages are defined by their implementation, so as long as it works with gcc I'm happy. Commented Apr 22, 2017 at 14:55
• I was just addressing the comment you included in your answer that it doesn't rely on any language extensions. Yes, even with language extensions, it's perfectly valid as an answer here, didn't mean to suggest otherwise.
– hvd
Commented Apr 22, 2017 at 15:04
• Ah, that's definitely fair. You're right that I should stipulate that, while no extra flags are required, this may not be portable. Commented Apr 22, 2017 at 15:58
• You can test for the empty string with *s instead of strlen(s). C strings are implicit-length, terminated by a char with value 0. Nice macro hack to allow call with/without an arg! Commented May 4, 2018 at 20:02

# 8086 machine code, 27 bytes

00000000  bb 00 00 85 c0 74 13 01  d8 be 00 01 89 e7 47 47  |.....t........GG|
00000010  57 b9 1b 00 f3 a4 5b 89  47 01 c3                 |W.....[.G..|
0000001b


This machine code must be at address 0x100, and assumes the tiny code model (cs=ds=es=ss). The function location can be changed without costing extra bytes, though. Putting it at offset 0 would save a byte (xor si,si instead of mov si, 0x100)

Required calling convention

This assumes the caller has pre-allocated at least 27 bytes on the stack. It takes a number in ax, and returns a function pointer in bx. Calling this pointer with ax=0 terminates the chain, and returns the sum in bx.
So for the first call:

mov bp, sp
sub sp, 28
call function
; new function pointer in bx


Then, for each subsequent call:

sub sp, 28
call bx
; new function pointer in bx


To terminate:

mov ax, 0
call bx
; result in bx
mov sp, bp


### Ungolfed (commented disassembly of the machine code):

00000000  BB0000            mov bx,0x0      ; 0 is replaced after copying
00000003  85C0              test ax,ax
00000005  7413              jz 0x1a         ; if(ax==0) ret (with value in bx)
00000007  01D8              add ax,bx       ; arg += total
00000009  BE0001            mov si,0x100    ; address of the original: ds:0x100
0000000C  89E7              mov di,sp
0000000E  47                inc di
0000000F  47                inc di          ; dst = sp+2 = above return address
00000010  57                push di
00000011  B91B00            mov cx,0x1b
00000014  F3A4              rep movsb         ; copy the function code.
00000016  5B                pop bx            ; bx = start of copy destination
00000017  894701            mov [bx+0x1],ax   ; update total in the copied code
0000001A  C3                ret               ; with bx = function pointer


After calling this with non-zero AX, bx = sp and the buffer is filled with a modified copy of the machine code from function. The 16-bit immediate in the first instruction holds the total. (It's written by the last instruction before the ret.)

push di / pop bx could be replaced with mov bx, di (before rep movsb), making it simpler but no savings.

Requiring the caller to pass a pointer to the dst buffer in di would save 4 bytes vs. calculating it relative to sp.

Making the function start address the same as the function size would save a byte (mov cx, si).

• This would be a better answer if you included disassembly of the machine-code bytes. machine-code answers definitely need an ungolfed version. e.g. use objdump -b binary instead of hexdump -C Commented May 4, 2018 at 20:05
• Updated with commented disassembly. Possible savings: require the caller to pass a dst pointer in di (4 bytes). Make the function start address = size: mov cx, si instead of mov cx, 0x1b. Commented May 5, 2018 at 17:34

# C (GCC), 83 bytes

My first C golf! There are a couple of other C solutions, but this one's a bit different. Preprocessor use is purely cosmetic. This approach was first discussed in Conor O'Brien's answer here.

#define r union r
t=0;r{int v;r(*f)();};r e;r f(a){t+=a;e.v=a?f:t;t*=a>0;return e;}


The terminal value is zero. The return value is a union, so to call the result, use field f, and to access the final value, use field v, e.g.

f(1).f(2).f(3).f(0).v


Try It Online

## Limitations

A global variable holds the running total. While this is explicitly disallowed, the submission does support repeated invocations (the total is reset in the terminal call), which seems to be the reason for the ban on global state.

A pointer to f is stored to the returned union through the int member, so this is clearly not portable. I'm not sure if this works on GCC on all platforms or just on Linux or just on x86 or just with ELF or... If anyone knows any details about this, please comment or send a message!

# APL (Dyalog Classic), 48474644 32 bytes

∇r←(a f)x
r←⍎'(a+x)f'↓⍨-0=x
∇
0f


Try it online!

Terminates by passing in zero . Call syntax: ((0 f 1) 2) 0

-15 bytes thanks to @ngn

Requires ⎕IO←0

Any golfing tips are welcome!

• if you can use 0 as terminator value, change :If x<0 to :If×x and swap the "if" and "else" clauses
– ngn
Commented May 25, 2018 at 3:22
• Derp. I didn't see that it said "non-positive" Commented May 25, 2018 at 3:33
• do you know this trick? r←⍎condition⊃'else' 'then'
– ngn
Commented May 25, 2018 at 4:42
• 32 bytes
– ngn
Commented May 25, 2018 at 4:59
• Thought that said 22... >_< Commented May 25, 2018 at 18:11

# Python 3, 39 bytes

class f(int):__call__=lambda s,o:f(s+o)


Try it online!

Not the shortest (by 3 bytes), but it's different from all previous Python approaches. It works by making a callable int subclass. Termination call is optional, but requires a 0 argument if used.

# Scala, 58 chars

case class f(n:Int){def apply(m:Int)=f(n+m)
def apply()=n}


Try it online

### Ungolfed:

case class f(n:Int){
def apply(m:Int)=f(n+m)
def apply()=n
}


### Explanation:

This code defines a case class called f with a constructor taking an int. Definind a case class which will generate the equals, hashcode, toString and copy methods, and a companion object with the same name to enable object creation without the new keyword.

This class has an overloaded apply method: One takes another integer to add and creates a new object with the updated sum, and one without arguments to get the sum.

In Scala, any object with an apply method can be called like a method, that is o.apply(x) can be written as o(x). This is used in the standard libary for arrays, lists, maps and the Function1 trait implemented by anonymous functions

# Java 8, 111 bytes

A lambda from int to a function. Calls are terminated by passing zero.

i->new java.util.function.Function<Long,Object>(){int t=i;public Object apply(Long x){t+=x;return x<1?t:this;}}


Try It Online

## Ungolfed

i ->
new java.util.function.Function<Long, Object>() {
int t = i;
public Object apply(Long x) {
t =+ x;
return x < 1 ? t : this;
}
}


Due to an interesting interplay between byte counts of primitive and object integer types, intermediate functions take a Long as a parameter, but the total is stored in and returned as an int.

## Limitations

The returned function is mutated when called, so, for instance, it's not possible to obtain two integer results without two calls of the lambda. However, the functions returned by separate calls to the lambda are fully independent, so it seems the challenge requirements are met.

Liberal casting is required when constructing expressions that use the lambda. See the TIO for a usage example.

• It's actually a lambda from int to an Object. Commented May 25, 2018 at 1:59
• Well you can cast it that way, but the actual return type isn't Object. Commented May 25, 2018 at 5:19

# Rust, 134 bytes

|x|{fn b(a:i32,n:i32)->Box<dyn std::any::Any>{if n>0{Box::new(Box::new(move|x|b(a+n,x))as Box<dyn Fn(_)->_>)}else{Box::new(a)}}b(0,x)}


Try it online!

In your face, strict type system! Terminates if the input is negative. You do have to downcast the result after every call though (see tio). I took a similar approach to the Math.js solution.

ungolfed:

|x| {
fn b(a: i32, n: i32) -> Box<dyn std::any::Any> {
if n > 0 {
Box::new(Box::new(move |x| b(a + n, x)) as Box<dyn Fn(_) -> _>)
} else {
Box::new(a)
}
}
b(0, x)
}


Rust's strong type system makes this almost impossible. Fortunately, trait objects come to the rescue. Trait objects erase the type and all associated data except for the trait's implementation. In this instance, I use the Any trait, which allows downcasting back into a concrete type. There are some wrinkles because you can't explicitly name the type of closures, so I have to cast the closure into a Fn trait object and then recast it into an an Any before use.

# Aussie++, 98 96 bytes

-2 because I remembered the angle brackets aren't necessary for a single-statement YA RECKON body.

THE HARD YAKKA FOR f IS(x)<THE HARD YAKKA FOR g IS(y)<YA RECKON y ?BAIL f(x +y);BAIL x;>BAIL g;>


Tested in commit 9522366. For the final call, give it BUGGER ALL or YEAH, NAH! instead of a number.

The general structure is something like

function f(x) {
function g(y) {
if (y) return f(x + y);
return x;
}
return g;
}


Since Aussie++ doesn't have function expressions or anonymous functions yet, it is necessary to put the function declaration and return as separate statements.

# Dyvil, 34 bytes

infix int apply(i:int,j:int=0)=i+j


Usage:

0() // = 0
0(1)() // = 1
0(1)(2)() // = 3


The trailing () can be omitted.

Explanation:

Defines a juxtaposition operator that takes two ints and adds them. The parameter j has the default value 0 to support the call without arguments. The 0 in the examples above is not the name, but a literal.

## C#, 62 bytes

dynamic f(int n)=>(System.Func<int,dynamic>)(m=>m<0?n:f(n+m));


To end the call pass in a negative number e.g.

f(1)(2)(3)(-1) == 6

• I'd like to get it to work by passing in null or no parameters to end. However, all the ways I tried were a lot longer Commented Apr 20, 2017 at 9:54
• Can you use !m instead of m<0 and pass null or 0 as the last parameter? Commented Apr 20, 2017 at 10:19
• @betseg No in C# only a Boolean can be be used as a Boolean... I tried with null but it just got longer. I wanted to use ?? which means if LHS is null do RHS, but as I need if LHS is not null do this else do RHS I couldn't. Commented Apr 20, 2017 at 10:23

# Pyth, 19 bytes

DhdDebR?bh+dbdR$end  Try it online! I'm impressed that Javascript beats Pyth, but then again Pyth is not quite designed to be passing functions. ## Perl 5, 36 bytes sub f{my$n=pop;sub{@_?f($n+pop):$n}}


say f(1)->(); # 1
say f(1)->(2)->(3)->(); # 6

• What about this requires -M5.016? It seems like you should be able to drop -M5.016 and then also drop my and save a couple bytes. If it's just say, you can use the flag -E instead, which doesn't activate use strict, so you can still drop the my. Commented Apr 22, 2017 at 22:30
• @Chris you're right, it doesn't need 5.16, my initial revision did (using __SUB__) but I changed that before submit and didn't remove the bit about 5.16. I'll remove that. I don't think dropping my would be correct though. Commented Apr 23, 2017 at 0:14
• (and no, I'm not counting say as part of the code, it's only for illustrative purposes) Commented Apr 23, 2017 at 0:14
• If you remove my without use strict, $n is implicitly a global variable. It's bad form in proper perl scripts, but it's pretty common in one-liners, and it seems to work here. Commented Apr 23, 2017 at 4:02 # Brain-Flak, 6 bytes Actually I just noticed that since the ToS is a valid return format popping the 0 is not really needed which saves 2 bytes: ({{}})  Try it online! ## Original submission(s), 8 bytes Uses 0 as the special value: ({{}}{})  Try it online! ### Explanation Given the arguments a1, a2, … , an, 0 the stack initially looks like this: an a2 a1 0 The code then goes on, pops every ai, accumulates them, pops the 0 adds them and pushes the result: ( ) -- push the following value: { } -- while ToS ≠ 0 (sums the runs): {} -- pop 1 element {} -- pop the remaining 0 & add it  ### Alternative solutions, 8 bytes Instead of popping the 0 and adding it to the sum, we can also swap stacks since the right one is initially empty: ({{}}<>)  Try it online! Using the -r flag the 0 is on the top of the stack, so we could pop it first: ({}{{}})  Try it online! {}({{}})  Try it online! • Oh my goodness... Great one! Commented Apr 15, 2018 at 15:29 # Nim, 135 bytes import sugar type X=object case t:int8 of 0:i:int else:f:int->X func s(x:int):int->X=(y:int)=>(if y<0:X(t:0,i:x)else:X(t:1,f:s x+y))  Try it online! Like the JavaScript answer, but with type safety. ## PHP7.4 (45 chars) The superglobal function$_ENV will return an adder function continuously.
After the operations, when no argument is provided $_ENV will return the result. The function$_ENV is not designed to accept a negative value or no input at all.

$_ENV=fn($a)=>fn($b=-1)=>~$b?$_ENV($a+$b):$a;


Usage :

var_dump($_ENV(1)() == 1); // bool(true) var_dump($_ENV(4)(2)(7)() == 13);          // bool(true)
var_dump($_ENV(4)(2)(7)(5)(2)() == 20); // bool(true)  Info: Overriding a superglobal like$_ENV variable isn't recommended.

Based on the explanation here

Named functions:

name args body
F a G(0,a)
G a, b IF(b>0,LAMBDA(c,G(a+b,c)),a)

Score: 34 (body text) + 2 (names) + 3 (args) = 39

### Example

Termination call arg is any non-positive number:

=F(2)(4)(0)


gives 6.

# Go, 87 82 bytes

func f(x int)func(int)any{return func(y int)any{if y<1{return x+y}
return f(x+y)}}


Attempt This Online!

Stopping value is 0.

This works because the any in Go represents all types, at the expense of every call after the 2nd needing to be cast with .(func(int)any), like f(3)(4).(func(int)any)(0).

• -5 by returning the function directly.

# Perl 6, 31 bytes

sub f(\n){->$m?{$m??f n+\$m!!n}}


## Python, 61 bytes

f=lambda n="":0if n==""else lambda m="":n if m==""else f(n+m)


Much longer than the other Python version, but uses the no-argument syntax rather than a magic number. Can probably be improved upon.

If it can be assumed that "at least one call will be made before the termination call", this can be reduced to 44 bytes:

f=lambda n:lambda m="":n if m==""else f(n+m)

• You can use 0 as default value and gain a bunch of bytes rearranging things: f=lambda n=0:n and(lambda m=0:m and f(n+m)or n)or n Commented May 6, 2018 at 11:17

## Julia v0.5+, 52 bytes

type F n end
F()=0
(f::F)()=f.n
(f::F)(x)=(f.n+=x;f)


Call as F. This could probably be made a lot shorter by adopting a less OO method, but I always like getting the chance to use this idiom.

If it can be assumed that "at least one call will be made before the termination call", the second line can be removed to save 6 bytes.