text:
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

Can we require a specific non-positive value as the terminator?

@Tutleman, not sure what it would lead to, let's say any non-positive should be OK to terminate the chain if this option is choosen

I don't understand what is being asked here. Can you ellaborate or clarify? What does the notation f(4)(2)(7)() mean?

@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.

@LuisMendo, it means 4 function calls, arguments on first 3 should be summed, because the forth call is "terminating"

@MartinEnder Thanks. So does the code need to return a function, or is that just one possible approach? Can it be a function with a "persistent" variable, such that the same function is called several times? This question is more for Eugene I guess

@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.

@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

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()?

Are functors allowed?

Apologies, I am not sure I understand. I have a 'plus over' function in k +/ ---- so +/[1 2 3] returns 6, is this incorrect? Do the arguments need to be (1)(2)(3)() - with parentheses AND a null terminator? What is the significance of the null terminator? If it isn't present should the function do nothing??

@EugeneD.Gubenkov Let me know when you clarify the above (whether the function should return a function or simply have memory across calls), so that I can remove my downvote

@Chromozorz the significance is currying and higher-order functions. I think a better title would be "Arbitrary-length Currying".

@LuisMendo, Please check out the updated description -- should be more precise now.

Arbitrary amount of function calls should be supported I believe some environment won't able to handle more than 1000 recursive call. It will simply throw StackOverflow error.

@ThariqNugrohotomo, let's go with 1000 as maximum sum, it is not critical to the spirit of the challenge

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.

I have some questions here. We can't use static storage so this function obviously needs some dynamically allocated buffer space. Does f() itself need to take care of that? Can f() take an additional parameter to a pre-allocated buffer? What about stack allocation? That has to be done (and eventually cleaned up) by the caller.

@CAD97 - I believe it is, although I don't have time to work on it right now.  The trick is that you can thread the expected output type of each function invocation backwards through in order to selected a typeclass instance at that invocation.  So just like read "123" can return either Int or Float depending on what the code calling it expects, f can have the type either VariadicFunction v => Int -> v or () -> Int depending on what's expected of it... It wouldn't be a short solution, but interestingly it may well be the only statically typed one on the list.

it should be f(4)(3)(), or the definitions should be flipped.

Does "any non-positive value" mean that we can e.g. specify 0 as the termination value and negative values as unsupported, or does it mean that, if we choose that option, the code must treat all non-positive inputs as termination values?

@CAD97 I haven't really learned Haskell yet, but I know that functions are curried by default. Does it have any varargs functionality? I found this.

Tangentially related.

Would a builder pattern be ok, i.e NewSum().Add(3).Add(4).Finish()?

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!

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.

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 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.

@ShreevatsaR: I see two definitions, f n()=n and f=(f.).(+), so I'd call it defining two functions.

@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.)

@ShreevatsaR: of course your example of the factorial function is just a single function. The two definitions in the code above are two individual definitions, because they are in different where contexts. Both f are of type Int -> a, so why shouldn't they be functions?

@nimi The first line says that, for a type a to belong to type class F, there must exist a function named f of type Int -> a. The next two lines declare that some types a belong to class F: namely types ()->Int, Int->(()->Int), Int->(Int->(()->Int)) and so on. For each of these types (call them a1, a2, ...), the "justification" that the type belongs to class F is given by defining corresponding (different) functions f, which are of types Int->a1, Int->a2, and so on. We could add more definitions for new types. (E.g. we could add instance F Char where f n = 'z'.)

@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.

Bending the rules a bit you could declare an instance for Int instead of ()->Int and claim that you "need" to use use 0 as a final argument, even though it isn't required, this would save you 7 bytes. Using () is nicer, but then again this is codegolf :)

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

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

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:

Cast the result to a function to tell the compiler you wish to call the result again;
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;}.

Try it online!

@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

Maybe function pointers? You'd have to de reference every time but might be worth checking out

Shame. Still, you can get rid of the typedef and simplify to q;f(x,o){return x?(q+=x,f):(x=q,q=0,x);} (Try it online!)

@Kevin That's fantastic!

@ConorO'Brien I just implemented your union approach. It's longer than this one, but it's not far off.

This solution seems to work fine when the function signature of f is reduced to just f(x)

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.

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.

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: 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.

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.

Ah, that's definitely fair. You're right that I should stipulate that, while no extra flags are required, this may not be portable.

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!

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).

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

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.

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

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), 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!

if you can use 0 as terminator value, change :If x<0 to :If×x and swap the "if" and "else" clauses

Derp. I didn't see that it said "non-positive"

do you know this trick? r←⍎condition⊃'else' 'then'

32 bytes

Thought that said 22... >_<

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.

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.

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

Can you use !m instead of m<0 and pass null or 0 as the last parameter?

@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.

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.

@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.

(and no, I'm not counting say as part of the code, it's only for illustrative purposes)

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.

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!

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.

Well you can cast it that way, but the actual return type isn't Object.

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.

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.

C#, 91 58 bytes
dynamic f(int x)=>(Func<int, dynamic>)(y=>y<1?x:f(x + y));

You can get rid of some spaces and the public .

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.

Perl 6, 31 bytes
sub f(\n){->$m?{$m??f n+$m!!n}}

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

I think the function should return (not print) $s. so you could do something like return$i?f:$s at the end

@ConorO'Brien I am not sure but if your Thinking is right it could save 5 Bytes Thank You

A few bytes can be saved with superglobal variables: function f($i){return[$_GET[0]+=$i][$i]?:f;}.

@user63956 a very nice idea

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

Julia 0.5, 18 bytes
!n=k->k>0?!(n+k):n

Try it online!

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

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}

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.

@KonradRudolph The golfed if was laziness, but the return is just for readability - it gives the same result with or without return.

@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.

Cool, I learned something new again. That's one reason I keep coming back. Thanks @KonradRudolph, also this Stack Overflow question is interesting: http://stackoverflow.com/questions/11738823/explicitly-calling-return-in-a-function-or-not

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

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!

Python, 69 bytes
def f(a=0,s=[]):
    if a:
        return lambda b=0:f(b,s+[a])
    return sum(s)

I'm assuming this is python? You should state the language used in your answer.

Can you try to golf your answer more? As it stands, it's not very well golfed.

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.)

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

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.

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.

C#, 53 bytes
Func<int,dynamic>f(int i)=>m=>m<0?(dynamic)i:f(m+i);

Any negative number can act as the stop value
int j = f(5)(3)(4)(-1); // j = 12

int j = f(-1); // Compile Error, must be 2 or more calls

Lua, 89 bytes
function f(...)n,p=...p=p or 0 return n and loadstring("return f(...,"..n+p..")")or p end

Well it's not exactly the shortest I see (Lua never is), but it was an interesting challenge. Had a lot of attempted arithmetic on a function and attempted to call a number along the way before the aha moment.
As a slight bonus though, it does work with non-positive numbers since nil and false are the only false values in Lua. In many golfing challenges, 0 ~= false is a drawback but not here!

k, 22 bytes
Call with a null value to terminate
{$[^y;+/x;.z.s[y,x]@]}

Example:
k)f:{$[^y;+/x;.z.s[y,x]@]}
k)g:f[3]
k)h:g[4]
k)h[0N] //0N is null integer in k
7

Clojure, 29 bytes
(defn f[n]#(if %(f(+ n %))n))

Example:
(for [f (->> [3 2 1 4 10] (reductions (fn [f val] (f val)) f) rest)]
  (f nil))
(3 5 6 10 20)

Attache, 20 bytes
{If[_,$&Sum[__],_2]}

Try it online!
Explanation
{If[_,$&Sum[__],_2]}
{                  }    lambda, taking parameters stored in `__`
 If[_,            ]     If the first parameter `_` is truthy (nonzero):
      $                    return this function
       &                   bonded with
        Sum[__]            the current running sum
               ,        otherwise:
                _2         return the sum

Since (f&n)[x] is equivalent to f[x, n], this will continue returning itself with the updated sum until n = 0.
If you want computation to occur after the final 0, then one could do this for 28 bytes:
{If[_,Fold[`&,$'__],Sum!__]}

This is much the same thing, except we use Fold[`&,$'__] to bond $ with each individual argument.

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.

Google Sheets, 39
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 bytes
func f(x int)func(int)any{g:=func(y int)any{if y<1{return x+y}
return f(x+y)}
return g}

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).


text:
Break my source file!
Challenge
Create a program that, when run, changes the contents of the source file. This means that you can delete/add/change characters in the source file, but you can't delete the (source) file itself (deletion is when the source file does not exist after the program is run).
In the case of pre-compiled languages such as C++, your program can change the source file only, such that when compiled, either fails or does not produce the same result.
Your program must not return any errors, such as access violations (e.g. opening a file that is already open).

This is an advantage to pre-compiled languages, as the source file does not have to be in use to run it.

Input
You may take an optional path to the source file, but nothing more.
Output
You may output anything.
Scoring
This is code-golf, shortest answer wins!

The title and the clarification for compiled languages suggest that the modification should stop the program from working afterwards, but the actual rules in your first paragraph make no mention of that.

@MartinEnder, the second paragraph suggests that the program must fail or the output must be different (which can be considered breaking it, since it no longer produces the output it used to).

@LuisMendo Probably fixed

Yes, I think it's better now

Can we assume the file name is a fixed string, such as f?

Can you hard code the file name and location?

Hi there! I've dupe-hammered this closed because even though the linked challenge is a popcon and this is a code-golf, many of the answers there are also valid and contenders here. Thanks!

@AdmBorkBork This question is about changing the source file. The dup is about damaging the program itself or the environment. That is not a duplicate.

@Notts90 Yes, as long as it works. Hell, put it in /bin/ if you like.

Re: the "is this a duplicate?" arguments: I immediately thought of Vigil for answering this question, looked at the duplicate that was linked, and saw Vigil as the top answer on +438. That said, many of the other answers won't transfer over; I guess this challenge is a subset of that one, rather than an exact copy, and am not sure how the duplicate rules apply to that.

Zsh, 3 bytes
>$0

Truncates the script to length 0.
Unlike its Bash counterpart, this handles filenames that contain whitespace.
Try it online!

C, 35 25 bytes
f(){fopen(__FILE__,"w");}

Just empties the source file.
Online test suite on TIO

but you can't delete the file itself. Clarification: the "file" in question is the source file.

@Thunda source file doesn't get deleted, it just gets emptied so it can't be compiled again.

I'd correct the "erase" term anyway.

Erase was a bit ambiguous there

I agree - I wasn't quite awake.

Octave, 27 bytes
fwrite(fopen('f','w'),'')

Explanation:
fopen('f','w') opens the file f (itself) with writing privileges (the file has no file extension (it's not f.m)). fwrite writes an empty string '' to that file, overwriting the content of it.
Run it from the GUI / CLI using: run f. PS!
Note: You should close the file again afterwards using fclose(3), but this is not necessary for it to work.

Python, 18 17 bytes
open(input(),"w")

-1 thanks to @EriktheOutgolfer
Opens itself in write mode, deleting everything in the file.

You can use input() getting quoted input (Python 2) or non-quoted input (Python 3) to the file path, because it's allowed by the rules. That saves 1 byte.

Jelly, 17 bytes
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»ŒV

Never fails, but produces different outputs.
Takes relative path through STDIN (unquoted).
Explanation:
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»ŒV Main link. Arguments: 0
“µ÷ⱮÑċẊṚ⁾Ṁ)ɦGl»   Literal "open(input(),'w')"
               ŒV Python eval and listify

Open a file in write mode in Python overwrites it.

PHP, 18
fopen(__FILE__,w);

From the manual:
Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file
does not exist, attempt to create it.

I guess that should also work in most other languages

Ruby, 10 bytes
open $0,?w

Not very original, almost everybody is doing it the same way nowadays.

C, 27 bytes
f(){system("cd>"__FILE__);}

Overwrites the contents of the file wtih the current directory.

Batch, 7 4 bytes
Thanks to Neil for saving 3 bytes
.>%0

> overwrites the contents of a file and %0 returns the current batch file's path.
Result: Blank batch file.

. is shorter than FC and still seems to work. I like the ~f but I would have thought you're allowed to require that the batch file is invoked including extension.

@Neil Indeed, thanks. I took another look and this might be the limit for Batch.

Node.js, 47 bytes
require('fs').writeFileSync(process.argv[1],'')

Erase the content of the source file

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Make text triangle waves
I was messing around on my 'ol TI-84 CE and made a program that produced this output (it was actually bigger but that is not the point):
 *
 *  *
 *  *  *
 *  *
 *
 *  *
 *  *  *
 *  *
 *
...

I evolved it to take input text and make the triangle waves out of that. The final step was to also take a number to specify the size (n>0). But I am super lazy so you must do it for me!
Challenge
Given a string and number (n > 0), output a triangle wave.  This should be in the following format (with * as the string input)
 *
 *  *
 *  *  *
 *  *  * *
 *  *  * * (...)
 *  *  * *
 *  *  *
 *  *
 *
 *
 *  *
 *  *  *
 *  *  * *
 *  *  * * (...)
 *  *  * *
 *  *  *
 *  *
 *
 (...)

Each line starts with 1 space on the left edge.
The first line should have * on the right edge, for a full line of *.
Every line after that, for the next n - 1 lines, you add *, <linenumber> times. So for n=3:

 *
 *  *
 *  *  *
 *  *
 *

Then, output this full triangle infinitely:

 *
 *  *
 *  *  *
 *  *
 *
 *  *
 *  *  *
 *  *
 *

Note that you can't have something like this, for n=2:
 *
 *  *
 *
 *
 *  *
 *

You must trim the repeated single *.
Another example, with a multichar string input:
'hi', 4 ->

 hi
 hi  hi
 hi  hi  hi
 hi  hi  hi  hi
 hi  hi  hi
 hi  hi
 hi
 hi  hi
 hi  hi  hi
...

Assorted other rules:

Output must be immediately visible (i.e. it will wait to display until the program ends)
You may take the input in any reasonable way, so ["hi",3] is allowed but ["h",1,"i"] is not. However, you may not use Ans to take input in TI-Basic programs.
You must continue the pattern forever, or until the program ends due to memory limits.
You do not need to have trailing spaces but leading spaces are required.
You must print up to one line at a time. (i.e. each line must be printed all at once, you can't print each triangle iteration by itself)
The one space padding is before and after each instance of the text

Here is an answer you can use to check your output. (with video)
Leading or trailing newlines are fine.
Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 117107; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Would it be acceptable to take the input with a trailing space? That is, the input * would be "*<space>", hi would be "hi<space>", etc.

@DownChristopher That is the standard method used for input for TI. Arbitrarily banning something a specific language uses just because you don't like it doesn't make sense.

Strange.  How is this question unclear?  It seems to be very well specified.

@mbomb007 what about prompt? It is not that I don't like it. It is that I view it as not reading the info we need

@DJMcMayhem hmm. That is a problem actually. If I allow that you may be able to golf it in an unfair way compared to others. Will using a trailing space make you sav.. actually if I let you anyone else can so sure

TIO also has a 128kb limit.

@Erik yeah I found that out fast

@DownChristopher Ans is TI's version of a function parameter.

@mbomb007 I personally don't like the use. I even posted my own answer to show how I believe it should work

@cleblanc, it wasn't me who cast that close vote, but I see the point of whoever it was. There isn't an actual spec: it has to be reverse engineered from two examples.

@PeterTaylor I don't see how anyone would not understand. I mean I have 17 answers and I personally have an example of code (I linked) with a running so people know what it looks like. Also the rules hold a large portion of the specs. But with examples there is no room for error

You do not have to wait until the time limit expires to make TIO show any output. Cancelling the request by clicking the run button for a second time will show all partial output up to that point.

You must print one line at a time, assuming this actually means having exactly one print statement per line of output, seems like a rather arbitrary rule. Why can't I print the output character by character. For input 3, why can't I print the four lines that constitute the pattern at once?

@Dennis Because it actually would make the answers a bit longer and allow more room for golfing. Otherwise it would be way to easy (it is still rather simple).

Arbitrary unobservable requirements, especially ones that make competing in some languages downright impossible, are a very poor way of making a challenge harder.

@Dennis How so? I suppose some languages. How about you cannot print more than one line at a time?

That should work well. That way BF languages could answer

@Christopher a bf solution coming up

@RohanJhunjhunwala Yees!

" *  *  * * (...)" what space rule?

05AB1E, 13 12 bytes
1 byte saved thanks to Erik the Outgolfer
[¹ð.ø²Lû¨×€,

Try it online!
Run locally if you want the lines displayed 1 at a time.
Explanation
[              # start infinite loop
 ¹ð.ø          # surround the first input by a space on each side
     ²Lû¨      # construct the range [1 ... n ... 2]
         ×     # replace each number in the range by that many instances of the string
          €    # for each string in the list
           ,   # print it on a separate line

Could also point out that the 2 warning messages at the bottom are indicative of infinite recursion in this specific case.

Haskell, 68 62 bytes
t#n=mapM putStrLn[[1..n-abs m]>>' ':t++" "|m<-[1-n..n-2]]>>t#n

Try it online! Example usage: "somestring" # 5.
Edit: Saved 6 bytes thanks to @Ørjan Johansen!
Given for example n=4, [1-n..n-2] constructs the list [-3,-2,-1,0,1,2]. For each element m in this list, [1..n-abs m] is a list of length n minus the absolute value of m, thus we get lists of length 4-3, 4-2, 4-1, 4-0, 4-1 and 4-2, that is 1, 2, 3, 4, 3 and 2. For each of this numbers >>' ':t++" " concatenates as many times the given string t with a space added to back and front.
This yields a list of strings with the first triangle. mapM putStrLn prints each of the strings in the list on a new line, then the function # calls itself again with the same arguments and starts over.

You can save 2 bytes with a list comprehension, and 2 more by shifting the indices and moving one item so that you get ([2..n]++[n+1,n..3]).

2 more bytes: [1..n-abs m] and [1-n..n-2].

@ØrjanJohansen Thanks a lot!

Java 7, 128 129 128 125 bytes
+1 byte: Missed the padding after each character
-1 byte: Changed k==1 to k<2
-3 byes thanks to Kevin Cruijssen
void a(String s,int i){s=" "+s;for(int j=-1,k=1,l;;k+=j){for(l=0;l<k;)System.out.print(s+(++l<k?" ":"\n"));j=k==i|k<2?-j:j;}}

First post here so let me know if I'm doing something wrong.  Any golfing help is much appreciated.
Try it online! Note: this times out after 60 seconds and then prints the results, the actual code continually prints infinitely
Ungolfed
void a(String s,int i){
    s= " " + s;

    for(int j=-1, k=1, l;; k+=j){
        for(l=0; l<k;)
            System.out.print(s+ (++l < k ? " " : "\n"));

        j = (k == i | k < 2) ? -j : j;
    }
}

Prepends a space to the input string then starts an infinite loop.  For each iteration it prints the string k times and then prints a new line.  k is then incremented / decremented based on the sign of j

Hi, welcome to PPCG! One thing you can golf is removing the int  from the second for-loop and adding ,l to the first for -2 bytes. Another thing you can golf is by changing if(k==i|k<2)j=-j; to j=k==i|k<2?-j:j; for -1 byte.

Thanks, I feel like I'm missing stuff that should be obvious, but I'm hopefully going to learn from this

For your first answer you did great, a lot better than when I joined! You automatically learn along the way. Just keep mental notes of golfing tips you come across, and if you haven't already, take a look at Tips for golfing in  and Tips for golfing in Java. Enjoy your stay! :)

Thanks.  I've done a bit (or a lot) of lurking around here so I've seen some of the standard things for golfing.  I just haven't gotten used to applying them

Scala, 79 Bytes
(s:String,n:Int)=>while(1>0)(1 to n)++(n-1 to 2 by-1)map(y=>println(s" $s "*y))

Try it online!
My first attempt at one of these.  The basic idea is to generate a sequence of numbers, from 1 to n, then concatenated with the reverse (minus the ends to avoid doubling up).  Then just loop over those numbers and print the input plus spaces that many times for each number in our generated sequence.
Ungolfed:
(text: String, n: Int) =>
  while(1 > 0) {                          //loop forever

    ((1 to n) ++ (n-1 to 2 by-1))       //Generate a sequence of numbers, from 1 to n
                                        //and then concatenate it with the sequence n-1 to 2

      .map(y=>println(s" $text " * y))  //for each number y in the sequence we generated,
                                        // print the input text, surrounded by spaces, y times
    }

Welcome to PPCG! Great first post!

Very well done! I like it!

C (gcc), 127 108 107 102 bytes
The loop in MACRO P prints each line, the for(j) loops print up and down the wave.
-5 byte thanks to ceilingcat.
#define P for(i=j;i--;printf(" %s%c",s,i?32:10))
i,j;f(s,n){for(;j++<n;)P;for(--j;j^1&&j--;)P;f(s,n);}

Try it online!

That is a mess. Can you explain?

99 bytes

Röda, 49 bytes
f n,s{{{seq 1,n;seq n-1,2}while[]}|print` $s `*_}

Try it online!

Jelly, 13 15 bytes
+2 bytes to fix up to print each line separately.
⁶;WṁÐ€ŒḄṖK€Ṅ€ȧß

Try it online! (note that TIO produces the would-be constant output only after it times out, errors, or, as in this case most likely, exceeds the text limit; offline it prints line by line.)
How?
⁶;WṁÐ€ŒḄṖK€Ṅ€ȧß - Main link: string s, integer n
⁶               - literal ' '
 ;              - concatenated with s
  W             - wrap in a list
   ṁÐ€          - mould like mapped over n (mould like [[1],[1,2],[1,2,3],...,[1,2,3,...,n]] - half of a sawtooth)
      ŒḄ        - bounce (reflect but only with one central element to make a triangle)
        Ṗ       - pop (remove the last element since the sawtooth triangles only have one shortest element between them, not two)
         K€     - join with spaces for €ach
           Ṅ€   - print and yield for €ach
             ȧ  - and
              ß - call this link with the same arity

C, 85 bytes
i,c,d;f(s,n)char*s;{for(;;)for(i=c+=d=c^n?c<2?1:d:-1;i;printf(" %s%c",s,--i?32:10));}

Python 3, 92 Bytes
from itertools import*
lambda b,a:[print(f" {b} "*(abs(i%(a*2-2)-(a-1))+1))for i in count()]

This code does require itertools, which is a native library in Python. I imported cycle as c.

@L3viathan That's what the question was asking? What do you mean?

@L3viathan I suppose I really should have just edited my comments instead of deleting, but basically, I fixed it.

Python 3, 124 108 94 90 89 bytes
r=range
x=lambda c,n:print('\n'.join(f' {c} '*i for i in[*r(1,n+1),*r(n-1,1,-1)]))+x(c,n)

Recursive lambda that would obviously error out if it ever got to evaluating itself (Adding an infinite sequence of Nones?). Thankfully, it doesn't!
It will still crash relatively soon, because of the default recursion limit, which can be overwritten using sys.setrecursionlimit(large_number)
Ungolfed:
def triangles(char, N):
    print(
        '\n'.join(
            # f' {char} ' is like ' {char} '.format(char=char)
            f' {char} ' * i
            for i in
            [*range(1, N+1), *range(N-1, 1, -1)]  # N=3 -> [1, 2, 3, 2, 1]
        )
    ) + triangles(char, N)

Nice! That one is cool

><>, 183 152 138 bytes
1+&01-1001.1+bc+-*4b{~p@-$*8b}:g1$1: <
>{:0)?v~{{1+$:@@:@)?v~>1+:&:&(?v>:c2*^
^   o:<v@-10oa0           v?(1:<
^      <    o" "@-10<.1*3b<

Try it online!
Takes a string and a number on the stack.
Explanation
# Initialization
1+&01-1001.
1+          Add 1 to value on top of stack (number from input)
  &         Store in register
   01-      Push 0 - 1 (-1) to stack
      10    Push 1 and 0 to stack
            (repetitions on this line, repetitions done for this line)
        01. Jump to row 1 column 0 and move
            (IP now on {)

# Output loop
>{:0)?v
^   o:<

{        Roll stack left
 :       Duplicate top of stack
  0      Push 0
   )     Greater than
    ?    If top of stack is nonzero (value > 0)
     v   Continue loop
      :  Duplicate top of stack
       o Output top of stack

# Line loop
>output~{{1+$:@@:@)?v

^           o" "@-10<

output                       Output word
      ~                      Delete -1 (end-of-word marker)
       {{                    Roll stack left twice
                             so the two repetition variables are on top
         1+                  Add one to repetitions done for this line
           $:@@:@            Duplicate both variables, preserving order
                 )           Greater than
                  ?          If nonzero (repetitions needed > repetitions done)
                   v         Continue loop
                    01-      Push -1
                       @     Roll top three items right so end-of-word marker is in correct place
                        " "  Push char code for space
                           o Output space

# Add newline
0ao01-@
0       Push 0 (repetitions done)
 a      Push charcode of newline (10)
  o     Output newline
   01-  Push -1
      @ Roll top 3 items right so end-of-word marker is in correct place

# Check if repetitions < 1
:1(?v
:     Duplicate (repetitions needed)
 1    Push 1
  (   Less than
   ?  If nonzero (repetitions needed < 1)
    v Continue loop (else add newline)

b3*1.
b3*            Push 11 * 3 (33)
   1           Push 1
    .          Jump to row 1 column 33 and move (IP was pointing left, so it is now on the second > in rebound loop)

# Rebound loop
          .1+bc+-*4b{~p@-$*8b}:g1$1: <
                     ~>1+:&:&(?v>:c2*^

~                                          Remove repetitions done for this line
 >                                         Make IP travel right (needed later)
  1+                                       Add 1 to top of stack (repetitions needed)
    :                                      Duplicate
     &:&                                   Get register value and store a copy back in register
        (                                  Less than
         ?                                 If nonzero
                                           (repetitions needed < input value + 1)
          v                                Check if repetitions < 1 (see above)
           >                               Make IP travel right (also needed later)
            :                              Duplicate top of stack (???)
             c2*                           Push 12 * 2 (24)
                :                          Duplicate
                 1                         Push 1
                  $                        Swap top two values
                   1                       Push 1
                    g                      Get value at row 1 column 24
                                           (initially the + near the start of this loop)
                     :                     Duplicate
                      }                    Roll right to put duplicate at bottom of stack
                       b8*                 Push 88
                          $                Swap
                           -               Subtract (turns '+' into '-' and vice versa)
                            @              Roll top 3 items to put at correct position
                             p             Put new character at row 1 column 24
                              ~            Delete ???
                               {           Roll stack left so original value of row 1 column 24 is back on top
                                b4*        Push 11 * 4 (44)
                                   -       Subtract
                                    +      Add to repetitions needed
                                     cb+   Push 12 + 11 (23)
                                        1  Push 1
                                         . Jump to row 1 column 23 and move (IP was pointing left, so it is now on the first >)

That is really cool. Right now you are going to win my bounty

PowerShell, 72 bytes
param($a,$b)$a=" $a ";if($b-1){for(){1..$b+($b-1)..2|%{$a*$_}}}for(){$a}

Try it online!
(TIO has a 60 second timeout, but please be nice to Dennis' server ... also note that TIO doesn't output (refresh the page) until the program completes, so you won't get on-the-fly output. Running this locally produces correct output.)
Straightforward. Takes input $a as the string and $b as the integer. We then pad $a with spaces and save it back. We then have an if check to handle the special case of $b=1. If $b>1 then this test is $TRUE and we enter the if.
Inside the if, we're entering an infinite for() loop. Inside the loop, we're constructing a range from 1 to $b and then $b-1 to 2. There are two possibilities here. If $b=2, this range is 1,2,1,2 and so we're actually constructing two triangles every for loop. If $b>2, then the range is something like 1,2,3,4,3,2 to construct one triangle every for loop. Inside the range loop, |%{}, we just string-multiply $a by the appropriate number.
If $b=1 then we don't enter the if, and so just enter a separate infinite for() loop that prints $a a bunch of times.
By default, PowerShell will "flush" the pipeline (for lack of a better term) on each for iteration, so that's where the implicit Write-Output happens.

Wow. That is cool. Don't worry about TIO I talked to Dennis and he said that it won't matter unless we all do this at once

JavaScript ES6, 98 bytes
s=>n=>{while(1){for(i=0;i++<n;)eval(p="console.log(` ${s} `.repeat(i))");i--;for(;--i>1;)eval(p)}}

Try it online!

CJam, 30 bytes
l~,:)_W%1>W<+S2*@*f*{_Nf+:o!}g

Try it online! (same as with other answers: TIO dumps all output after 60 seconds, you have to run it locally to see the proper behaviour)
Explanation
Example input: "hi" 4
l~     e# Read an eval a line of input
       e# STACK: ["hi" 4]
,:)    e# Generate the range 1 ... N
       e# STACK: ["hi" [1 2 3 4]]
_W%    e# Duplicate and reverse it
       e# STACK: ["hi" [1 2 3 4] [4 3 2 1]]
1>W<   e# Slice to remove the first and last elements of the copy
       e# STACK: ["hi" [1 2 3 4] [3 2]]
+      e# Concatenate
       e# STACK: ["hi" [1 2 3 4 3 2]]
S2*    e# Push "  "
       e# STACK: ["hi" [1 2 3 4 3 2] "  "]
@*     e# Bring the text to the top and join the space string with it
       e# STACK: [[1 2 3 4 3 2] " hi "]
f*     e# Repeat the resulting string by each number in the range
       e# STACK: [[" hi " " hi  hi " " hi  hi  hi " .....]]
{      e# Do:
 _     e#  Duplicate the top
       e#  STACK: [[" hi " " hi  hi "...] [" hi " " hi  hi "...]]
 Nf+   e#  Append a newline to each string in the top array
       e#  STACK: [[" hi " " hi  hi "...] [" hi \n" " hi  hi \n"...]]
 :o    e#  Pop and print each string in the top array (one by one)
       e#  STACK: [[" hi " " hi  hi "...] []]
 !     e#  Boolean negation
       e#  STACK: [[" hi " " hi  hi "...] 1]
}g     e# While the top of stack (popped) is truthy
       e# STACK: [[" hi " " hi  hi " " hi  hi  hi " .....]]

Excel VBA, 97 79 Bytes
Anonymous VBE immediate Window Function that takes input of String from cell [A1] and variant/String of assumed type integer from cell [B1] and outputs a triangle wave using those values to the VBE immediate window.
n=[B1]:Do:DoEvents:For i=1To n*2-2:[C1]=n-Abs(i-n):?[Rept(A1&" ",C1)]:Next:Loop

Jelly, 13 bytes
⁾  jẋŒḄ}ṖṄ€1¿

Try it online!
How it works
⁾  jẋŒḄ}ṖṄ€¹¿  Main link. Left argument: s (string). Right argument: n (integer)

⁾  j           Join "  " with separator s, prepending and appending a space to s.
     ŒḄ}       Bounce right; yield [1, ..., n, ..., 1].
    ẋ          Repeat (" "+s+" ") 1, ..., n, ..., 1 times, yielding a string array.
        Ṗ      Pop; remove the last string.
           1¿  While 1 is truthy:
         Ṅ€      Print each string, followed by a linefeed.

That is some fast code. Good job

TI Basic 210 Bytes
Prompt Str4
Prompt N
0->V
Lbl A
0->S
If (S=0
Then
0->B
1->S
Else
1->B
End
" "->Str1
Str1->Str2
Str1+Str4+Str1->Str5
0->P
Lbl B
If (S=1 and B<N)
Then
B+1->B
Str1+Str5->Str1
Disp Str1
0->P
End
Goto B
Else
For(H,N-1,2,-1)
0->R
" "->Str1
While (R<H)
Str1+Str5->Str1
End
Disp Str1
End
Goto A

Running it (video)

The least you could do is remove the pointless parentheses

@Zacharý they have to be there iirc

You remembered incorrectly, because right parens can be elided at the ends of lines, like you did on line 6

Batch, 108 bytes
@set f=@for /l %%i in (2,1,%1)do @call echo %%s:.= %2 %%^&call set s=%%s
@set s=.
%f%%%.
%f%:~1%%
@%0 %*

Conveniently I both need to use the current value of a string in a for loop and substitute into it with another variable. Ungolfed:
@echo off
setlocal enabledelayedexpansion
set s=.
:l
for /l %%i in (2, 1, %1) do echo !s:.= %2 !&set s=!s!.
for /l %%i in (2, 1, %1) do echo !s:.= %2 !&set s=!s:~1!
goto l

Groovy, 82 80 bytes
{s,n->s+=" ";a=0;x={println s*a};for(;;){for(;a<n;a++){x()};for(;a>1;a--){x()}}}

Previous answer
{s,n->s+=" ";a=0;x={println s*a};for(;;){while(a<n){x();a++};while(a>1){x();a--}}}

Ungolfed (previous answer)
h={s,n->  //A closure with two arguments, the input text and the size of the wave peak
    s+=" " //add a space after the input text
    a=0    // a counter we will use later
    x={println s*a}  //another closure that prints the input text repeated "a" times
    for(;;){  //infinite loop
        while(a<n){  //two while loop that make "a" oscillate between 1 and "n", printing at each iteration
            x()
            a++
        }
        while(a>1){
            x()
            a--
        }
    }
}

Groovy man groovy

Lua, 104 bytes
p=print;function f(s,n)c=" "..s;while(0)do p(c)for i=2,n+n-2 do p(c:rep(i<=n and i or n+n-i))end end end

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Are these lists equal?
As you may very well know python has lists.  As you might not know these lists can contain themselves.
a = []
a.append(a)

Python 2
Python 3
These are cool and there are lots of interesting things you can do with them, however you cannot compare them.
a = []
a.append(a)
b = []
b.append(b)
a == b

Python 2
Python 3
Task
Your job is to write a function in Python (or any language that can handle python objects directly) that will take two lists that may contain themselves and compare them.
Two lists are equal if they are the same length and there does not exist sequence of numbers such that indexing both of the lists by that sequence results in two objects that are not equal under this definition of equal.  All non-list objects contained in a list will be python integers for simplicity and should be compared with python's builtin equality for integers.
Your program should not rely on the recursion depth of python to determine if a list is infinitely deep.  That is:
def isInfinite(a,b):
 try:
  a==b
  return False
 except RunTimeError:
  return True

Is not a valid way of determining if two lists are self referential.
Testcases
Assumes you define a function equal
a = []
a.append(a)
b = []
b.append(b)
print(equal(a,b))

True

a = []
b = []
a.append(b)
b.append(a)
print(equal(a,b))

True

a = []
b = []
a.append(1)
a.append(b)
b.append(1)
b.append(a)
print(equal(a,b))

True

a = []
a.append(a)
b = [a]
print(equal(a,b))

True

a = []
b = []
c = []
a.append(b)
b.append(c)
c.append(a)
equal(a,b)

True

a=[1,[2]]
b=[1,[2,[1]]]
a[1].append(a)
b[1][1].append(b[1])

True

a = []
a.append(a)
b = [1]
b.append(a)
c = [1]
c.append([c])
print(equal(b,c))

False

a = []
b = []
a.append(1)
a.append(b)
b.append(a)
b.append(1)
print(equal(a,b))

False

a = []
b = []
a.append(a)
b.append(b)
b.append(b)
print f(a,b)

False

As a side note to potential voters: Note that generally language specific challenges are frowned upon except for in certain circumstances (like tasks that are only interesting in certain languages). IMO, this is a wonderful example of a language-specific challenge.

@WheatWizard That's not exactly enough -- the nested lists need to also be the same lengths as well.

@WheatWizard You actually can compare them. In Python, you only get a "recursion limited exceeded" if they aren't equal. https://tio.run/nexus/python2#@5@oYKsQHcuVqJdYUJCal6KRqMmVBBFKQhIqKMrMK1FItLVN@v8fAA

@mbomb007 Thats because python by default compares the references.  If you have two identical objects that have different references it fails, hence the challenge.

Additional test case: a = [] b = [] c = [] a.append(b) b.append(c) c.append(a) f(a, b). Tests loops of size > 1.

I don't know if it is OK to golf this in another language, because the code will be obviously longer than python solution...

Should the submissions be reusable? E.g. should it be possible to call the function many times and always get the correct answer?

@isaacg Yes they should.

Can you extend this challenge to all languages where lists can contain themselves?

Is it okay to destroy the input lists? Or should they remain unmutated?

@AkshatMahajan They should remain unmuted.

@KeyuGan, Python code can be shorter in non-Python languages!

Technically, in a = [];a.append(a);b = [a], they're not equal. The infinity of a would be one less than the infinity of b. If you can assume they're not equal, then I believe repr(a)==repr(b) would work (tested in 3.6.1).

@zgrep Since the infinity we are concerned with is cardinal not ordinal they are the same size.

@WheatWizard Ah, I see. Okay.

Python 2, 94 bytes
g=lambda c,*p:lambda a,b:c in p or all(map(g((id(a),id(b)),c,*p),a,b))if a>[]<b else a==b
g(0)

Try it online!
An improvement on isaacg's very clever solution of storing the id pairs of lists being processed and declaring them equal if the same comparison comes up on a lower level.
The recursive step all(map(...,a,b)) says that a and b are equal if all corresponding pair of elements in them are equal. This works nicely to reject unequal-length because map pads the shortest list with None, unlike zip which truncates. Since none of the actual lists contain None, these padded lists will always be rejected.

What is the purpose of the , after the c?

It makes it a tuple.

a=[];a+=[a,1];b=[];b+=[b,2];f(a,b) overflows the stack, and a=[1];b=[2];f(a,b);f(a,b) looks like a reusability problem.

@AndersKaseorg I see, mutating the list was asking for trouble. I think this fixes it.

@AndersKaseorg And I see you wrote basically the same function-in-a-function solution. There's a 95-byte solution without that: f=lambda a,b,p=[0]:p[0]in p[1:]or all(map(f,a,b,[[(id(a),id(b))]+p]*len(a)))if a>[]<b else a==b. Maybe there's a nicer way to handle the map.

@xnor So I had a really bad idea…

Python, 233 218 197 217 bytes
d=id
def q(a,b,w):
 w[(d(a),d(b))]=0
 if d(a)==d(b):return 1
 if(a>[]and[]<b)-1:return a==b
 if len(a)!=len(b):return 0
 for x,y in zip(a,b):
  if((d(x),d(y))in w or q(x,y,w))-1:return 0
 return 1
lambda a,b:q(a,b,{})

The anonymous function on the last line performs the desired function.
This is still in the process of being golfed, I just wanted to show that this is possible.
Essentially, we put an entry in w if we're working on a given check. Two things are equal if they're the same object, if they're not lists, and they're equal, or if all their elements are either equal or being worked on.

Can't you use a>[] instead of i(a,list)?

@mbomb007 This was written before the "Everything is lists or ints" rule was added. Will update.

You can use a>[]<b and len(a)-len(b)

@ETHproductions Oh, his byte count is wrong. That's why

Can d(a)==d(b) be a is b? That would cut two uses of d.

You can do w[d(a),d(b)]=0 instead of w[(d(a),d(b))]=0.

Test suite

The 4th and 5th lines can be combined to make if(a>[]<b)-1or a is b:return a==b

In fact the 6th line can also be combined because python checks that the lists are the same size before it starts the recursion.  if(a>[]<b)-1or len(a)-len(b)or a is b:return a==b

... and the last 3 lines can be combined into a list comprehension. link

3 more bytes

Another 3 more by putting it on one line

a=[1];b=[2];q(a,b);q(a,b) looks like a reusability problem.

@AndersKaseorg Is there an expectation of re-usability? If so, I can clear w after each run, but I don't think that's a requirement.

Do function submissions have to be reusable?


text:
Restricted powers of two
Challenge
Given a number x, output the first x powers of two, starting with 2¹ (2).
Example
2   2 4
3   2 4 8
1   2
6   2 4 8 16 32 64

You may output numbers separated by non-numerical characters. You may not just output them mashed together like 248163264128.
Rules

In your code, you may only use the number 2. You may not use any other numbers, either as ASCII characters or numeric literals in any base.

You may not use character literals as integers to bypass this rule.

You may not use your language's built-in exponentiation function, operator, or similar. You must implement the exponent yourself.

You may not use bit shifting operators.
You may not use operations that are equivalent to bit shifting.

Standard loopholes are disallowed.
This is code-golf, shortest answer wins. However, it will not be selected.

In my opinion this is the worst type of restricted source challenge.  It is really impossible to verify whether or not a particular program contains a number other than 2 objectively.  Each language becomes its own separate argument about what is and is not allowed.  For restricted source challenges you should be able to write a computer program that can verify if a particular program obeys the rules.

This is a Do X without Y challenge. I reccomend checking out things to avoid doing in challenges

In my language there is a « operator that in docs is "bitshift left" but is programmed as multiply by two. Can I use that?

"or similar" what does this mean? Anything which performs repeated multiplication? This is a really fuzzy line which will only be tested in code-golf

@Downgoat "Or similar" applies to "function, operator". For example, a stack operation or modifier.

@Mendeleev so I have a 2^N operator which isn't an exportation op/func, can I still use that? It's not exponentiation but according to your wording it's OK

@Downgoat No.

If I'm using C can I use a char as a number?  It's not a number in any base but it acts like one

@Mendeleev Probably should specify that

(This could have really benefitted from some time in the Sandbox ...)

I'm not even sure what the purpose of disallowing 2 is. Why would you need any other numbers unless you're using an esolangs where numbers are part of the usual syntax in which case you're just disallowing the entire language for no good reason...

@StewieGriffin Accidentally middle clicked.

@AdmBorkBork The Sandbox has mostly been a bad experience for me. Almost every time I've psoted there, the challenge has been mostly ignored.

@Mendeleev likely because it's a boring challenge.  If it's at all interesting, you're sure to get either votes or feedback.  And bad feedback is not being ignored, that's constructive criticism (idk if you've had any of that though).

@Riker Have not had any feedback

What do you expect to gain by not allowing anything but 2? 99% of languages don't need anything else, and the ones that do are mostly number based esolangs.

I can see loopholes in two of the restrictions without even spending any time to think about it. Predefined variables which by default hold numeric values but which aren't numeric literals bypass the restriction on using numbers; base conversion bypasses the restriction on exponentiation.

Haskell, 20 bytes
(`take`iterate(*2)2)

Try it online!
3 bytes longer than the unrestricted:
f n=map(2^)[1..n]

Alice, 16 bytes
t/O<\*2Hw&
k\i.@

Try it online!
Explanation
This uses the w&...k looping technique explained in this answer.
t    Decrement the implicit zero on top of the stack to give -1 to initialise
     the product for later.
/    Reflect to SE. Switch to Ordinal.
i    Read all input as a string.
     Bounce off bottom boundary, move NE.
<    Set the horizontal component of the IP direction to west, i.e. move NW.
     Bounce off top boundary, move SW.
i    Try reading more input. Just pushes an empty string.
     Bounce off bottom boundary, move NW.
/    Reflect to W. Switch to Cardinal.
t    Implicitly discard the empty string and convert the actual input to its
     numerical value N. Decrement it to get N-1.
     IP wraps around to the last column.
&w   Repeat the following bit N times.
  H    Take the absolute value of the top of the stack. This is only
       relevant for the first iteration, because we initialised the product
       to -1 instead of 1.
  2*   Double the current product.
  \    Reflect to SW. Switch to Ordinal.
  .    Duplicate the current product (also converts it to a string, but it
       will be converted back by the H).
       Bounce off bottom boundary, move NW.
  O    Output the current product as a string with a trailing linefeed.
       Bounce off top boundary, move SW.
  \    Reflect to W. Switch to Cardinal.
k    End of loop.
     IP wraps around to the last column.
@    Terminate the program.

Cheddar, 26 bytes
n->2/2|>n=>n->[n]*n/(*)

Takes n as art generated range [1, n], maps (=>) It over [n]*n (array of n n times over multiplication)
No TIO link because cheddar on TIO is outdated.

Jelly, 5 4 bytes
2ṁ×\

Try it online!
How it works
2ṁ×\  Main link. Argument: n

2ṁ    Mold; reshape [2] as [1, ..., n], generating an array of n 2's.
  ×\  Take the cumulative product.

Brain-Flak, 44 bytes
(([{}]){}<(()())>){({}<((({})){})>()())}{}{}

Try it online!
Explanation:
#Push negative(input * 2)
(([{}]){}

  #And push a 2 underneath it
  <(()())>
)

#While True:
{

    #Pop the top of the stack off
    ({}

       #And double the number underneath it
       <((({})){})>

    #Then push the former top of the stack + 2
    ()())

#Endwhile
}

#Pop two elements, implicitly display stack
{}{}

38 bytes

Octave, 23 bytes
@(x)cumprod(~(2/2:x)+2)

Try it online!
Returns cumulative product of repeated 2s.

JavaScript (ES6), 35 bytes
x=>[...Array(x)].map(_=>p+=p,p=x/x)

Using no digits at all.

SOGL, 6 bytes
2.{t2*

Explanation:
2       push 2
 .{     repeat input times
   t     output
    2*   multiply by two

Ruby, 29 bytes
->n{b=2;n.times{puts b;b*=2}}

Python 2, 31 bytes
n=2
exec"print n;n*=2;"*input()

Try it online!
This might be the shortest way to do it, restrictions or no. Compare
lambda n:[2<<i for i in range(n)]
# 33 bytes, ignoring restrictions

Try it online

CJam, 11 bytes
2ri{_p2*}*;

Try it online!

Batch, 80 bytes
@set/px=
@set/ap=2/2
@for /l %%i in (%p%,%p%,%x%)do @set/ap+=p&call echo %%p%%

Takes input on STDIN, since %1 would be illegal. Fully illegal version would only be 63 bytes:
@set/ap=1
@for /l %%i in (1,1,%1)do @set/ap+=p&call echo %%p%%


text:
Count occurences of a set in a list
Given a non-empty set of strings and a list of strings, find out how many times the set occurs in the list, i.e. how many times you could create the set with items from the list. Every element from the list can only be used once.

Hint: a set is an unordered list of unique items.

Default input/output rules apply.
No external libraries allowed. Compiler/Interpreter standard libs are okay. This is code golf, so shortest solution counts.

Test cases:
["apple", "banana"], ["apple", "pear", "apple", "banana", "banana"] => 2

["apple", "banana"], ["apple", "pear", "apple", "banana", "apple"] => 1

["apple", "banana", "pear"], ["apple", "banana", "kiwi", "apple"] => 0

["coconut"], [] => 0

EDIT: removed a sentence stating that the input params are defined in local scope. This contradicts the default IO rules linked above.

Yes that clarifies it.  However I am a little hung up on the third sentence.  What do you mean by "doesn't handle objects"?

@WheatWizard some languages are not object-oriented and don't know the concept of comparing arbitrary objects.

You should probably change that to object-oriented because every language I am aware of does handle objects of some type even if objects are a closed class.  I should also point out that there are a good deal of languages that also cannot handle strings at all.

@WheatWizard okay, updated description. That paragraph was meant for languages such as C, Assembler or Maple.

What languages are object oriented? What should they use if not strings? I think the easiest thing would be to restrict to just strings. Or, alternatively, only integers. See this advice on using the simplest type that suffices.

Good point, @xnor. updated. I think the solutions so far are all handling strings just fine, so this won't invalidate any.

@AdmBorkBork nope! will add another test for that.

The set is non-empty. The list can be empty.

OK, I would suggest to explicitly add that. Like "Given a non-empty set of strings and a potentially-empty list of strings" or similar, because as it's currently written my brain reads it as both the set and the list are non-empty.

For future reference, I'll also direct you to the Sandbox where you can post challenges, get meaningful feedback, and tweak them before they're posted to main.

@AdmBorkBork thanks. much appreciated.

Related: Three fruit pies

Python, 30 bytes
lambda s,l:min(map(l.count,s))

Try it online!

Nice one. Didn't think about using map. You can save a little by using print instead of defining a lambda BTW.

@HubertGrzeskowiak Changing the lambda to a print brings the byte count up to 37 because of the two input()s required.

@WheatWizard as stated in the challenge, consider the inputs defined in local scope. You are NOT required to have the inputs explicitly defined, e.g. as function params or user inputs.

@HubertGrzeskowiak if there is no good reason for it, you should not overwrite our defaults for taking input and output and our defaults for codegolf submissions

@ovs oh, I wasn't aware of that post. Thanks.

Jelly, 6 5 4 bytes
ċ@€Ṃ

Try it online!
The first argument of the program is the set, and the second argument is the list.
Explanation
ċ@€Ṃ
ċ@   -- Create a link which finds the number of occurrences of
          its left argument in its right argument (the list)
  €  -- Map this link over each element in the first argument
          of the program (the set)
   Ṃ -- Minimum value of this.

-1 byte thanks to @ETHproductions
-1 byte again thanks to @ETHproductions

Very nice! You can save a byte by combining the links into one line: ⁹ċ$€Ṃ I have a feeling that can be made shorter by using the implicit right argument in place of ⁹...

I think ċ@€Ṃ works to save another byte... (the @ reverses the arguments to ċ)

@ETHproductions Works correctly as far as I have tested.

It didn't exist until May 12 of last year, but Ɱ in place of @€ (with reversed arguments to the program) saves yet another byte: Try it online!

Jelly, 4 bytes
⁼þSṂ

Try it online!
How?
⁼þSṂ - Main link: list theSet, list theList
 þ   - outer product using the dyadic operation:
⁼    -     is equal? (non-vectorising)
  S  - sum (vectorises) (yields the number of times each element of theSet appears in theList)
   Ṃ - minimum (can only make the minimum as a multiple)

JavaScript (ES6), 56 bytes
f=(n,h)=>Math.min(...n.map(c=>h.filter($=>$==c).length))

Try it online

Save 2 bytes by using an anonymous function and another by currying the parameters: n=>h=>Math.min(...n.map(c=>h.filter($=>$==c).length)) for 53 bytes

JavaScript (ES6), 64 bytes
(s,l)=>l.map(e=>m[s.indexOf(e)]++,m=s.map(e=>0))&&Math.min(...m)

Assumes both s and l are arrays of objects. Uses JavaScript strict equality for comparisons, so for instance [] === [] is false.

Very interesting solution. Please return or print the result. AFAIK this returns an anonymous function.

@HubertGrzeskowiak The code as shown evaluates to an anonymous function. When called, the function returns the count as desired.

Haskell, 37 34 bytes
Thanks to @Laikoni for shaving off three bytes.
s#l=minimum[sum[1|y<-l,y==x]|x<-s]

Call with (set::[a]) # (list::[a]) where a is any type deriving Eq.

Instead of  length[y|y<-l,y==x] you can use sum[1|y<-l,y==x].

@Laikoni, are you sure about that? I think I would need to use something like sum[1|y<-l,y==x,_<-y], which comes out to two bytes longer—I could definitely be missing something there, though

Never mind, you're definitely right. Good call.

CJam, 11 bytes
q~f{\e=}:e<

Try it online!
Explanation
q~           e# Read and eval the input
  f{\e=}     e# Map each item in the set to the number of times it appears in the list
        :e<  e# Find the minimum of the resulting list

Mathematica, 24 bytes
Min[#/.Rule@@@Tally@#2]&

Pure function taking two lists as arguments in the suggested order and returning a nonnegative integer. Tally counts how many occurrences of every symbol occur in the input list, and #/.Rule@@@ converts each element of the input set into the corresponding number of occurrences.

T-SQL, 62 59 bytes
Previous version didn't work for sets with no matches
select top 1(select count(*)from l where l=s)from s order by 1

With s and l as tables and columns named the same as the table
select top 1         -- return only the first result
    (select count(*) -- count of rows
     from l          -- from table l
     where l=s)      -- for each l equal
from s               -- to each from s
order by 1           -- sort by count ascending

Swift, 39 bytes
s.map{w in l.filter{$0==w}.count}.min()

explanation:
s.map{} goes through each word in s and will produce an array of counts
w in  names the mapped word for use in the next filter
l.filter{} aplies a filter to the l array
$0==w is the filter condition matching word w
.count gives the number of elements of l that met the condition
.min() returns the lowest count in the mapped result

Welcome to PPCG! I've added code formatting for your solution. You can do this by prepending 4 spaces to lines that contain code.

APL (Dyalog), 9 bytes
⌊/+/⎕∘.≡⎕

Try it online!
⎕ get evaluated input (list of strings)
⎕∘.≡ get evaluated input (non-empty set of strings) and create equivalency table
+/ add across
⌊/ minimum across

C++, 203 201 bytes
Thanks to @Quentin for saving two bytes!
#import<vector>
#import<string>
using T=std::vector<std::string>;
int f(T S,T L){for(int j,b,i=0;;++i)for(auto s:S){for(b=j=0;j<L.size();++j)if(L[j]==s){b=1;L.erase(begin(L)+j);break;}if(!b)return i;}}

Try it online!

L.begin() -> begin(L) saves one byte :)

Also, using T=std::vector<std::string>; saves another! Who knew modern pretty syntax could also help golfing.

@Quentin I tried that at first. Probably there was some simple typo I didn't notice.

Suggest j<L.size()&!b;++j)if(b=L[j]==s)L.erase(begin(L)+j); instead of j<L.size();++j)if(L[j]==s){b=1;L.erase(begin(L)+j);break;}

Perl 6,  37  18 bytes
37
{+(($_=@^a⊍@^b)≽@a)&&.values.min}

Try it
Expanded:
{
  +( # turn into a 0 if False

    (
      $_ =        # store into $_ the result of
        @^a ⊍ @^b # use the baggy multiplication operator
    ) ≽ @a        # is that the baggy superset of the set
  )

  &&          # if that is True

  .values.min # get the minimum value from the Bag in $_
}

See Sets, Bags, and Mixes for more information.

18
{@^b.Bag{@^a}.min}

Try it
Explanation:
@^b.Bag create a Bag from the values
{@^a} key into that Bag (returns a list of counts)
.min get the minimum value of the resulting list

Neat answers, but neither of these look like functions / complete programs

@JulianWolf I was under the impression that snippets were allowed based on the statements “Consider both inputs being defined in the current scope as s and l.” and “You don't need to define a function.” I went and edited it anyway.

Ah, you're completely right. That must've been edited into the question after I read it. In any case, I like the aesthetic of this version even more than the last—Perl's syntax will always be a mystery to me.

@JulianWolf This isn't really a good example of Perl 6 code. I would recommend seeing Ovid's 1hr talk Perl 6 — Why People Are So Excited, or looking at the Resources tab on Perl6.org.

Yeah, sorry for the confusion. This is my first chllenge and I didn't know there already are rules for input and output. I changed it because most answers were using these rules even while it wasn't required.

@HubertGrzeskowiak Those are default rules, you could have specifically stated that snippets were also allowed. (Don't do it after people have posted golfs)

Axiom, 42 bytes
f(a,b)==reduce(min,[count(x,b)for x in a])

test code and results
(28) -> f(["1","2"], ["1", "2", "1", "1", "7"])
   (28)  1
                                                    Type: PositiveInteger
(29) -> f(["apple","banana"],["apple","pear","apple","banana","banana"])
   (29)  2
                                                    Type: PositiveInteger
(30) -> f(["apple","banana"],["apple","pear","apple","banana","apple"])
   (30)  1
                                                    Type: PositiveInteger
(31) -> f(["apple","banana","pear"],["apple","banana","kiwi","apple"])
   (31)  0

Java, 114 Bytes
<T>int a(Set<T>b,List<T>c){int m=2e32;b.stream().map(i->{int j=java.util.Collections.frequency(c,i);m=j<m?j:m;});return m;}

Tio coming soon
Explanation

creates local variable m.
maps the set to a stream.
for each element, if the number of occurances of the element in the list is less than m, m is set to that value.
returns m, which is the number of complete versions of the set

PHP, 74 Bytes
<?foreach($_GET[0]as$v)$t[]=array_count_values($_GET[1])[$v];echo+min($t);

Testcases
PHP, 108 Bytes
<?[$x,$y]=$_GET;echo($a=array_intersect)($x,$y)==$x?min(($a._key)(array_count_values($y),array_flip($x))):0;

Testcases

C#, 36 bytes
f=(n,h)=>n.Min(c=>h.Count(x=>x==c));

n and h are string[] and the output is an int.
Try it online!
This answer is inspire by @ovs and @Alberto Rivera's logic. Thank you!

Java, 135 bytes
int f(List<String> s,List<String> l){int n=0,i=0;while(i<s.size()){if(!l.remove(s.get(i++)))break;if(i==s.size()){n++;i=0;}};return n;}

This is my first code golf challenge and answer, so not sure about the format. Does it need to be a full compiling program? Do I need to define the parameters? Suggestions appreciated.
EDIT: wrapped code in a function. Thanks @Steadybox

An answer can be a full program, a function or some other function-like construct. You can take the parameters for example as arguments to a function or from standard input.

Pyth, 5 bytes
hS/LF

Takes the list first and the set second.
Test suite.
Explanation:
    F  Expand the input into l and s (not literally,
                  since those are function names in Pyth, but...)
   L   for d in s:
  /        Count instances of d in l
   L   Package all the results as a list
 S     Sort the results smallest-first
h      grab the smallest element

05AB1E, 7 bytes
v²y¢})W

Try it online!
v   }   # For each item in the first list...
 ²y¢    # Count the occurances in the second list.
     )W # Take the minimum occurrence count, return.

R 54 Bytes
f<-function(s,l) min(table(factor(l[l%in%s],levels=s)))

Explanation: creating a table of the counts of only the values in the list that also appear in the sublist.
I then turn the variable into a factor in order to generate zeros if a value that appears in the sublist does not appear in the list. Finally, I take the minimum of the counts.

R, 61 57 44 bytes
print(min(sapply(s,function(x)sum(l%in%x))))

Anonymous function. Apparently you don't have to define a function for this challenge. Saved 13 bytes thanks to count.
Explanation:
sum(l%in%x)) returns the number of times a string in s is found in l.
lapply(s,function(x)) applies that to each string in s separately and returns a list of sums.
min() returns the smallest from that list.

Could be brought down to 40 Bytes with a for-loop: z=c();for(i in s)z[i]=sum(l%in%i);min(z)

Or even further to 37 bytes with sapply: min(sapply(s,function(x)sum(l%in%x)))

Brilliant, I always forget you can sum booleans. I'll edit that in later. I've been told I need that print() if it's not a function.

JavaScript (ES6), 59 bytes
a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0

Try it

f=

a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0

console.log(f(["apple","banana"])(["apple","pear","apple","banana","banana"]))
console.log(f(["apple","banana"])(["apple", "pear", "apple", "banana", "apple"]))
console.log(f(["apple","banana","pear"])(["apple","banana","kiwi","apple"]))
console.log(f(["coconut"])([]))