53
\$\begingroup\$

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
\$\endgroup\$
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ – Martin Ender Apr 19 '17 at 21:42
  • 6
    \$\begingroup\$ @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. \$\endgroup\$ – Martin Ender Apr 19 '17 at 21:49
  • 6
    \$\begingroup\$ @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 \$\endgroup\$ – Luis Mendo Apr 19 '17 at 21:58
  • 4
    \$\begingroup\$ 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()? \$\endgroup\$ – Conor O'Brien Apr 19 '17 at 22:08
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – CAD97 Apr 20 '17 at 7:06

38 Answers 38

49
\$\begingroup\$

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;
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ Brilliant submission! \$\endgroup\$ – Eugene D. Gubenkov Apr 19 '17 at 19:21
21
\$\begingroup\$

Haskell (GHC), 118 bytes

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – nimi Apr 20 '17 at 20:45
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ – ShreevatsaR Apr 21 '17 at 4:44
  • \$\begingroup\$ @ShreevatsaR: I see two definitions, f n()=n and f=(f.).(+), so I'd call it defining two functions. \$\endgroup\$ – nimi Apr 21 '17 at 5:27
  • 7
    \$\begingroup\$ @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.) \$\endgroup\$ – ShreevatsaR Apr 21 '17 at 5:53
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – ShreevatsaR Apr 21 '17 at 18:34
15
\$\begingroup\$

Python 2, 42 41 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
\$\endgroup\$
14
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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;}. \$\endgroup\$ – Kevin Apr 20 '17 at 6:48
  • \$\begingroup\$ Try it online! \$\endgroup\$ – Kevin Apr 20 '17 at 6:48
  • 1
    \$\begingroup\$ @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 \$\endgroup\$ – Conor O'Brien Apr 20 '17 at 11:14
  • \$\begingroup\$ Maybe function pointers? You'd have to de reference every time but might be worth checking out \$\endgroup\$ – Downgoat Apr 20 '17 at 14:04
  • 1
    \$\begingroup\$ @ConorO'Brien I just implemented your union approach. It's longer than this one, but it's not far off. \$\endgroup\$ – Jakob May 24 '18 at 20:00
13
\$\begingroup\$

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.
\$\endgroup\$
  • 1
    \$\begingroup\$ <3 symbolic programming \$\endgroup\$ – Julian Wolf Apr 19 '17 at 23:41
8
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Beautiful. And not just the golfed solution...overloading operator() to make this work was especially cool. \$\endgroup\$ – Ray Toal Nov 2 '17 at 3:10
6
\$\begingroup\$

Ruby, 23 bytes

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

Usage:

f[1][2][3][nil]
=> 6
\$\endgroup\$
6
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$ – Dennis Apr 20 '17 at 18:54
4
\$\begingroup\$

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!

Explination

LaTeX!

As shown in the above LaTex, 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), which takes one argument, which loops. Adding to the value of y.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ "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? \$\endgroup\$ – hvd Apr 22 '17 at 14:18
  • \$\begingroup\$ @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. \$\endgroup\$ – Julian Wolf Apr 22 '17 at 14:55
  • \$\begingroup\$ 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. \$\endgroup\$ – hvd Apr 22 '17 at 15:04
  • \$\begingroup\$ Ah, that's definitely fair. You're right that I should stipulate that, while no extra flags are required, this may not be portable. \$\endgroup\$ – Julian Wolf Apr 22 '17 at 15:58
  • \$\begingroup\$ 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! \$\endgroup\$ – Peter Cordes May 4 '18 at 20:02
4
\$\begingroup\$

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
mov ax, number_to_add
call function
; new function pointer in bx

Then, for each subsequent call:

sub sp, 28
mov ax, number_to_add
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).

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Peter Cordes May 4 '18 at 20:05
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Cordes May 5 '18 at 17:34
2
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – TheLethalCoder Apr 20 '17 at 9:54
  • \$\begingroup\$ Can you use !m instead of m<0 and pass null or 0 as the last parameter? \$\endgroup\$ – betseg Apr 20 '17 at 10:19
  • \$\begingroup\$ @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. \$\endgroup\$ – TheLethalCoder Apr 20 '17 at 10:23
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Perl 5, 36 bytes

sub f{my$n=pop;sub{@_?f($n+pop):$n}}

say f(1)->(); # 1
say f(1)->(2)->(3)->(); # 6
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Chris Apr 22 '17 at 22:30
  • \$\begingroup\$ @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. \$\endgroup\$ – hobbs Apr 23 '17 at 0:14
  • \$\begingroup\$ (and no, I'm not counting say as part of the code, it's only for illustrative purposes) \$\endgroup\$ – hobbs Apr 23 '17 at 0:14
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Chris Apr 23 '17 at 4:02
2
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Oh my goodness... Great one! \$\endgroup\$ – Eugene D. Gubenkov Apr 15 '18 at 15:29
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

APL (Dyalog Classic), 48 47 46 44 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!

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

Perl 6, 31 bytes

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

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Julia 0.5, 18 bytes

!n=k->k>0?!(n+k):n

Try it online!

\$\endgroup\$
1
\$\begingroup\$

R, 40 bytes

f=function(x)function(y)`if`(y,f(x+y),x)

0 acts as the stop value here. For two more bytes, we can omit it.

The problem is that R lacks a concise built-in lambda. But if we add one, we can get the code to 26 bytes:

f=x->(y->`if`(y,f(x+y),x))

(Yes, that’s valid R. It just needs an import.)

\$\endgroup\$
1
\$\begingroup\$

PHP, 44 Bytes

An Idea from @user63956

Termination call 0

function f($i){return[$_GET[0]+=$i][$i]?:f;}

Online Version

Termination call with NULL need a càst [$i] to [+$i]

PHP, 47 Bytes

function f($i){global$s;return$i?f.!$s+=$i:$s;}

Online Version

PHP, 52 Bytes

Termination call NULL or any other value that is false in PHP

function f($i){global$s;$i?$s+=$i:print$s;return f;}

if the program must terminate after the Output replace print$s with die("$s") + 2 Bytes

Online Version

\$\endgroup\$
  • 1
    \$\begingroup\$ I think the function should return (not print) $s. so you could do something like return$i?f:$s at the end \$\endgroup\$ – Conor O'Brien Apr 19 '17 at 22:35
  • \$\begingroup\$ @ConorO'Brien I am not sure but if your Thinking is right it could save 5 Bytes Thank You \$\endgroup\$ – Jörg Hülsermann Apr 19 '17 at 23:07
  • 1
    \$\begingroup\$ A few bytes can be saved with superglobal variables: function f($i){return[$_GET[0]+=$i][$i]?:f;}. \$\endgroup\$ – user63956 Apr 20 '17 at 5:46
  • \$\begingroup\$ @user63956 a very nice idea \$\endgroup\$ – Jörg Hülsermann Apr 20 '17 at 10:54
1
\$\begingroup\$

PowerShell, 86 bytes

$f={$n=$args[0];$f=(gv f).value;{if($args){&$f($args[0]+$n)}else{$n}}.getnewclosure()}

Try it online!

Test code:

&(&(&(&(&(&$f 4)2)7)5)2)

Output: 20

\$\endgroup\$
  • \$\begingroup\$ Very nice. Welcome to PPCG! You can save a byte by doing $n="$args" instead of $n=$args[0]. It won't work on the other $args[0], though, because then you'll get string concatenation rather than addition. \$\endgroup\$ – AdmBorkBork Apr 20 '17 at 12:57
1
\$\begingroup\$

Python 3, 63 bytes

f=lambda n,l=[]:n and(l.append(n)or f)or sum(l)*(l.clear()or 1)

Try it online!


Terminates with 0

\$\endgroup\$
1
\$\begingroup\$

Python, 69 bytes

def f(a=0,s=[]):
    if a:
        return lambda b=0:f(b,s+[a])
    return sum(s)
\$\endgroup\$
  • 1
    \$\begingroup\$ I'm assuming this is python? You should state the language used in your answer. \$\endgroup\$ – corvus_192 Apr 20 '17 at 10:13
  • \$\begingroup\$ Can you try to golf your answer more? As it stands, it's not very well golfed. \$\endgroup\$ – Rɪᴋᴇʀ Apr 20 '17 at 14:23
1
\$\begingroup\$

Octave, 39 bytes

function r=f(n)r=@(m)merge(m,f(m+n),n);

*Argument of the termination call is 0.

Try it online!

*endfunction required to add some other codes.

\$\endgroup\$
1
\$\begingroup\$

R, 54 52 bytes

f=function(x){g=function(y='')'if'(y>'',f(x+y),x);g}

Saved 2 bytes thanks to MickyT!

Similar to one of the python answers. Ungolfed:

f=function(x){
  g=function(y=''){
    if(y>''){
      f(y+x)
      }
      else{x}
  }
  g
}

Runs as

> f(1)(2)(4)()
[1] 7
\$\endgroup\$
  • 1
    \$\begingroup\$ Nice work. You can get rid of the internal braces around the if clause. f=function(x){g=function(y='')'if'(y>'',f(x+y),x);g} \$\endgroup\$ – MickyT Apr 20 '17 at 3:42
  • \$\begingroup\$ I’m a bit puzzled why your “ungolfed” version has return. return in R isn’t the same as in other languages, it performs a premature abort. Not using return is idiomatic. On the other hand your ungolfed version still has the golfed if. \$\endgroup\$ – Konrad Rudolph Apr 20 '17 at 10:21
  • \$\begingroup\$ @KonradRudolph The golfed if was laziness, but the return is just for readability - it gives the same result with or without return. \$\endgroup\$ – BLT Apr 20 '17 at 14:02
  • \$\begingroup\$ @BLT Hm. I feel strongly that gratuitous in R return decreases readability because it signals the wrong thing (premature exit) and is an instance of cargo cult programming. \$\endgroup\$ – Konrad Rudolph Apr 20 '17 at 14:03
  • \$\begingroup\$ Cool, I learned something new again. That's one reason I keep coming back. Thanks @KonradRudolph, also this Stack Overflow question is interesting: stackoverflow.com/questions/11738823/… \$\endgroup\$ – BLT Apr 20 '17 at 14:08
1
\$\begingroup\$

C++ (gcc), 95 91 bytes

struct f{int s;f(int t):s(t){}int operator()(){return s;}f operator()(int t){return s+t;}};

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.