40
\$\begingroup\$

Using your language of choice, write a function that takes a variable number of arguments and returns the number of arguments it was called with.

Specifics:

  • Your language needs to support variadic argument functions: something callable that takes an arbitrary number of arguments and returns a value.
  • Parameters must be able to be passed individually. This means that passing an array would only count for one parameter. You can use an "all passed arguments" array if your language supports it; the restriction is on how the function is called.
  • Code that calls this function must not be required to pass the number of arguments in its source. If a compiler inserts the number of arguments as part of a calling convention, that is allowed.
  • The arguments can be of any type you want. You can support only a single type (e.g. only supporting int is still valid), arbitrary types (any type of argument is allowed), or any combination of argument types (e.g. first arg is int, rest are strings).
  • Your function may have a maximum number of arguments (especially since resources are finite), but must support at least 2 arguments.

Samples:

  • f() returns 0
  • f(1) or f("a") returns 1
  • f([1, 2, 3]) returns 1 as it is passed an array, not 3 arguments
  • f(1, 10) or f(1, "a") returns 2

As this is code-golf, the winning solution is the one that uses the fewest number of bytes.

\$\endgroup\$
21
  • 6
    \$\begingroup\$ It's not entirely clear (objectively) what is a "function", "return value" or "variadic arguments". For example, would Dodos function be considered as monadic or variadic? \$\endgroup\$
    – DELETE_ME
    Apr 10, 2018 at 5:06
  • 27
    \$\begingroup\$ @user202729 If your language doesn't support functions, use another language. It's not a requirement that all languages can compete, part of code golfing is finding the right tool for the job. \$\endgroup\$
    – Sanchises
    Apr 10, 2018 at 7:46
  • 5
    \$\begingroup\$ @user202729 I have no problems with the occasional challenge aimed at traditional/high-level languages, just as we have the occasional challenge that is only possible in unusual languages. \$\endgroup\$
    – Sanchises
    Apr 10, 2018 at 13:58
  • 7
    \$\begingroup\$ didn't know we had to solve the halting problem for language characteristics to have a clear challenge.... \$\endgroup\$ Apr 11, 2018 at 2:06
  • 6
    \$\begingroup\$ If your language doesn't have the concept of arguments / calling convention then it doesn't fit the criteria of supporting arbitrary numbers of arguments. \$\endgroup\$ Apr 11, 2018 at 8:23

81 Answers 81

1 2
3
0
\$\begingroup\$

SimpleTemplate, 23 bytes

In this language, all functions have some special variables.

Luckly, one of them is argc, which contains the number of arguments passed to the program or function.

{@fna}{@returnargc}{@/}

This could be written as {@fna}{@returnargc} if it was the last thing in the file.

Alternativelly, running {@returnargc} by itself gives you back the number of arguments passed to the program itself.


Ungolfed:

{@fn a}
    {@return argc}
{@/}

All whitespace present here is optional.


Example: count the arguments passed to the function

{@fna}{@returnargc}{@/}

{@call a into b 1, 2, 3, 4, 5, 6}

{@echo b}

How to run:

  1. Get the code from https://github.com/ismael-miguel/SimpleTemplate
  2. Run the following code:

    <?php
        include 'SimpleTemplate.php';
    
        $template = new SimpleTemplate('<code>');
    
        $template->render();
    
  3. Done!

(Shamelessly lifted from Print a word clock and adapted for this challenge)

\$\endgroup\$
0
\$\begingroup\$

REXX, 12 bytes

return arg()

arg without arguments returns the number of arguments.

\$\endgroup\$
0
\$\begingroup\$

Wolfram Language (Mathematica), 9 bytes

Length@*f

Try it online!

Composition of the Length function, which returns the number of arguments of an expression, and the undefined function f.

\$\endgroup\$
0
\$\begingroup\$

Scheme, 16 bytes

(λ a(length a))

Or defining a named function (25 bytes):

(define(f . a)(length a))
\$\endgroup\$
0
\$\begingroup\$

Yabasic, 17 bytes

An anonymous function that takes input as discrete arguments and outputs to the console.

?peek("argument")

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Brainfuck, 27

>>,[>,]<[[-]<[<]<+>>[>]<].

Try it online!

"arguments" are single characters. output is in ASCII (eg 32 args outputs a space). In order to see output normally, add this thing that I stole from esolang wiki (204 bytes)

>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<

Explanation

>> padding
,[>,] input all
<[ for each
  [-] delete
  <[<]< go back to beginning
  + add one
  >>[>] go to the end
<] go back
<. print
\$\endgroup\$
0
\$\begingroup\$

Lua, 30 bytes

function f(...)return#{...}end

Try it online!

Explanation: ... is used to pass variadic arguments, {...} creates a new table and expands the argument list into that table, and # is the length operator (for arrays, returns number of elements).

\$\endgroup\$
0
\$\begingroup\$

Funky, 10 bytes

(...a)=>#a

Funky does this pretty well. I first tried @#arguments, however, arguments is never actually used by @ functions, and even if, that turned out larger...

Try it online!

\$\endgroup\$
0
\$\begingroup\$

C#, 32 bytes

int X(params int[] y)=>y.Length;

Expression-bodied method with the params keyword.

\$\endgroup\$
0
\$\begingroup\$

Clojure, 11 bytes

#(count %&)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

C macro (gcc), 61

  • 3 bytes saved thanks to @ceilingcat.

I think the only way to do this in is with a preprocessor macro:

#define f(a...) ({char*s=#a,i=!!*s;for(;*s;)*s++-44||i++;i;})

Any symbols and literal integers may be passed. But passing literal strings containing commas will certainly mess this up.

This can probably be golfed more, but for now its a proof-of-concept.

The arg counter is declared as a char, and is thusly size-limited.

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ You can remove the space between f(a...) and ({char*s \$\endgroup\$
    – ceilingcat
    Jun 16, 2018 at 3:39
0
\$\begingroup\$

Visual Basic .NET (.NET Core), 54 49 bytes

Unfortunately, lambda expressions do not allow ParamArray in VB.net.

Function F(ParamArray a())
F=a.Count:End Function

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 49? \$\endgroup\$
    – ASCII-only
    Jun 9, 2018 at 5:35
  • \$\begingroup\$ @ASCII-only Oh, I forgot that's how values used to be returned in old VB syntax. That should work. \$\endgroup\$
    – mbomb007
    Jun 9, 2018 at 19:28
0
\$\begingroup\$

Python 2,22 21 15 bytes

lambda*a:len(a)

EDIT: -1 byte by removing space between "lambda" and "*a"

Edit 2: -6 thanks to @ppperry

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I believe you can save a few bytes by removing the "print" \$\endgroup\$ Aug 7, 2018 at 3:00
0
\$\begingroup\$

W, 1 byte

If I'm understanding it correctly:

k

Why does this work?

Assume that the program is a function (the program is technically a function). In this case, you pass arguments into the function in a list like this:

[[item1,item2,item3]]

Because the main list only supports at most 4 items, we put the arguments in a sub-list of that list (just an optimization, no effect for the source code).

Also, the program technically reads that list of arguments:

ak

Then it finds the length of a list of its arguments.

\$\endgroup\$
0
\$\begingroup\$

K (ngn/k), 2 bytes

#:

Try it online!

This is a lame answer, honestly.

\$\endgroup\$
0
\$\begingroup\$

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes

L#X

Try it online!

L#X
L   # Length
 #X # Of the argument list
\$\endgroup\$
0
\$\begingroup\$

J-uby, 7 bytes

:>>&:+@

Attempt This Online!

The :>> operator gathers all of the arguments into an array; :+@ returns its length.

\$\endgroup\$
0
\$\begingroup\$

Pip, 2 bytes

#G

Attempt This Online!

Note that Pip's function-call syntax does not support calling a function with zero arguments, so instead I'm using the V operator (call function with given argument list) with an empty list for that test case.

Explanation

All functions in Pip are variadic. The list of arguments can be accessed through the local variable g.

 G  ; Variable preset to {g}, a function that returns its argument list
#   ; Length
    ; The result is a function that returns the length of its arglist
\$\endgroup\$
0
\$\begingroup\$

TypeScript's type system, 57 bytes

interface F{o:this extends{i:{}[]}?this["i"]["length"]:0}

Try it at the TS playground!

I'm not entirely sure if this is valid, because it's not exactly a "function" in the traditional sense, but it is very similar.

Normal TypeScript type submissions are defined with the type keyword, and take input via generic type parameters:

type Greet<T extends string> = `Hello, ${T}!`
type Something = Greet<"World">
//   ^? "Hello, World!"

These work as functions in most cases, but there are two main cases in which they don't suffice:

  • Higher order functions - you can't pass a generic type as an argument to another generic type.
  • Variadic arguments - usually this is handled by taking a list as the argument.

There is actually another way to define "functions" in TypeScript, though- one which solves both of these problems, albeit in an extremely hacky way:

interface Greet {
  o: this extends { i: [infer S extends string] } ? `Hello, ${S}!` : never
}

type Something = (Greet & { i: ["World"] })["o"]
//   ^? "Hello, World!"

Within the interface, it checks if its own type has a property i, and if it does, does something with that value, otherwise returning nothing.

What's very hacky about this is that when you take the intersection type of Greet and a record type which has a property i, Greet takes its own type to have that property.

I couldn't tell you why the TypeScript team decided to make this be the behavior, but it comes in very handy in cases like this.

Since this behavior is rarely used and almost certainly unintentional, there isn't a very common calling convention for these, but the most common one I've seen is taking either a tuple of ordered arguments from a property, or taking a record of named arguments from that property. I've opted to use the former for this submission, as it makes the problem very convenient and short.

\$\endgroup\$
0
\$\begingroup\$

RProgN 2, 2 bytes

)L

Same concept as many stack based answers; collects everything on the stack into a stack, and gets its length.

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Submission has to be a function, this looks to be a program taking arguments on the command line? \$\endgroup\$
    – noodle man
    Jan 19 at 0:01
  • \$\begingroup\$ @noodleman Full programs haven't been forbidden elsewhere. Either way, prepending ² to this (giving ²)L) makes a function with the exact same functionality. \$\endgroup\$
    – ATaco
    Jan 19 at 0:26
  • \$\begingroup\$ I think other submissions to this challenge which aren't functions are invalid, per the spec "Using your language of choice, write a function that takes a variable number of arguments and returns the number of arguments it was called with." \$\endgroup\$
    – noodle man
    Jan 19 at 1:56
  • \$\begingroup\$ @noodleman To argue against this solution is to invalidate numerous others (And disqualify languages without functions). The only way to confirm it, would be to invoke the challenge author directly. I think it's safe to assume this is a valid submission for now \$\endgroup\$
    – ATaco
    Jan 19 at 2:45
-1
\$\begingroup\$

Python, 3 bytes

len

Attempt This Online!

Using the new community default that multiple arguments to a function can be taken as a list instead.

Named function which accepts a list of variable length and returns its size.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ IMHO default IO methods don't apply when the challenge explicitly specifies a IO method \$\endgroup\$
    – mousetail
    Apr 22, 2023 at 9:24
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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