How many arguments were passed?

33

1

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.

Glenn Smith

Posted 2018-04-10T03:00:11.363

Reputation: 585

3What if the language doesn't allow functions... – user202729 – 2018-04-10T04:49:08.453

5It'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? – user202729 – 2018-04-10T05:06:28.650

4(I downvoted because the challenge requires unobservable requirements) – user202729 – 2018-04-10T05:15:48.163

24@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. – Sanchises – 2018-04-10T07:46:26.550

2I've already deleted my C and assembly answers, but I figured I'd ask anyway: do answers have to work for any number of arguments, or is it OK if there's an upper limit (in this case: 8). – Dennis – 2018-04-10T13:22:28.507

"the arguments can be of any type; you do not need to support all types or arbitrary types of arguments" -- does that mean we can support a single type of our choosing? – Giuseppe – 2018-04-10T13:34:41.013

2@Sanchises Some language-specific restrictions are acceptable (being able to read /dev/urandom or time or access argv). I don't like this restriction which make use of the definition of "function" and "variadic" in a language. – user202729 – 2018-04-10T13:38:56.207

5@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. – Sanchises – 2018-04-10T13:58:53.467

@Sanchises But this requirement is not objective. ... – user202729 – 2018-04-10T14:00:00.170

Does the number have to be printed, or can it be from stderr? – Stan Strum – 2018-04-10T14:41:46.970

3Solutions that (I think) under dispute: Haskell (that's not variadic argument, that's multiple curried), Dodos (count argv, while "technically" according to the language spec each function take a vector of numbers), Batch (also count argv), Brain-Flak (Brain-Flak doesn't have the concept of "function"), Japt (right in the answer there is "take all of the inputs as an array"), CJam (technically CJam doesn't have "input to function", just a global stack, the calling convention must be made up, according to the answer), APL (see Dennis' comment below the answer), maybe more but I don't know. – user202729 – 2018-04-10T15:59:42.163

Either the challenge is unclear (in defining what's a function and what's variadic) or too many people misunderstand the specification. – user202729 – 2018-04-10T16:02:08.677

Is "something callable that takes an arbitrary number of arguments and returns a value" specific enough? If a language does not have the concept of a function, then it cannot support variadic functions. – Glenn Smith – 2018-04-10T17:10:42.647

3The problem isn't that it's not specific, the problem is that whether a calling convention counts as taking several arguments individually or not, is for many languages a property of a description of the language, or of internal details of how it is implemented, not of the visible behavior of the language itself. – Ørjan Johansen – 2018-04-10T17:44:00.153

1

@user202729 The fact that the Haskell function uses currying shouldn't be an issue.

– user9549915 – 2018-04-10T19:45:53.340

2

@GlennSmith I suggest asking about this question in meta. This question is not doomed to be closed and people there might say what they think would make the question more clear.

– dylnan – 2018-04-10T22:47:36.767

@user9549915 ... ØrjanJohansen is correct. | Functions can take multiple arguments as an array of arguments too (yes, why not?)... – user202729 – 2018-04-11T00:39:46.803

6didn't know we had to solve the halting problem for language characteristics to have a clear challenge.... – Conor O'Brien – 2018-04-11T02:06:50.147

Elaborated on calling conventions (as long as you don't have to pass the length in source it's valid) and maximum number of arguments (>= 2) – Glenn Smith – 2018-04-11T07:52:20.293

How is "passing an array" different from "passing multiple arguments"? What if our language doesn't have a calling convention (Assembly, CJam) and you have to make up one? You need extra clarification about that. – user202729 – 2018-04-11T08:14:24.723

5If your language doesn't have the concept of arguments / calling convention then it doesn't fit the criteria of supporting arbitrary numbers of arguments. – Glenn Smith – 2018-04-11T08:23:40.870

Answers

15

Amstrad CPC Z80 binary call from BASIC, 1 byte, hex encoded

C9          : RET

(Also 2 and 5 byte versions, see below)

Upon entry to the call, the number of parameters passed will be in the A register. The code simply returns immediately. There is no concept of return values in the Z80, just entry and exit states. The value is just "there" accessible in the register since the code changes no input conditions, except for PC (the program counter) and SP (the stack pointer). However, the value in A is not accessible to BASIC and gets overwritten almost immediately.

Examples:

CALL &8000, "Hello", "World"

A = 2

CALL &8000, 42

A = 1

CALL &8000

A = 0


By request, here is some code that makes the value accessible in BASIC. I was very surprised to find it could be done in only 5 bytes!:

The machine code:

12          : LD   (DE), A
13          : INC  DE
AF          : XOR  A
12          : LD   (DE), A
C9          : RET

On entry:

  • AF - the accumulator and flags registers (treated as two 8-bit registers)
    • A contains the number of parameters passed, up to the maximum of 32 parameters
    • I'm not sure what's in F. It appears to have all flags RESET to 0, except the two undefined flags which are both 1. The Z flag (zero) is SET to 1 if there were no parameters passed in
  • BC
    • B - 32 minus the number of parameters (A + B = 32)
    • C - &FF
  • DE - The address of the last parameter, or the calling address if no parameters were passed in
  • HL - The address of the first byte after the tokenised BASIC command currently being executed (either as a program or in immediate command mode)
  • IX - The stack address of the pointer to the last parameter
  • IY - &0000

The code

  1. LoaDs the address pointed to by DE with the value in A
  2. INCrements DE
  3. XORs A (with A), giving &00
  4. LoaDs the value in A to the address pointed to by DE
  5. RETurns

On exit:

  • A is destroyed (it's always &00)
  • DE is destroyed (it's always one higher than on entry)
  • All other registers are preserved

The BASIC

Amstrad basic has only three data types, plus simple arrays. By default, all BASIC variables are REAL (signed, 32 bit mantissa, 8 bit exponent), which can be made explicit with !. For an INTEGER (signed, 16 bit) use % and for a STRING (1 byte string length, up to 255 bytes character data, binary safe) use $:

  • x - REAL (implicit)
  • x! - REAL (explicit)
  • x% - INTEGER
  • x$ - STRING

You can also use DEFINT, DEFREAL and DEFSTR with a single letter, or a range of two single letters to specify the default type for all variables starting with that letter, similar to FORTRAN.

  • DEFSTR a
  • DEFINT x-z

Now:

  • a - STRING (implicit)
  • i - REAL (implicit)
  • x - INTEGER (implicit)
  • x$ - STRING (explicit)

The easiest type to work with is the integer. The machine code expects the last parameter to passed by address, not value, which is why @ is prefixed to the variable. The return variable is counted as one of the CALLs parameters.

The machine code is called as follows from BASIC (assuming it's loaded at into memory at address &8000):

CALL &8000, "Hello", "World", 42, @n%

n% = 4

This will always give the correct result, regardless of the initial value of n%.

For a 2-byte version that preserves all input registers:

CALL &8003, "Hello", "World", 42, @n%

n% = 4

This skips the first three bytes, and only gives the correct result if the initial value of n% is 0-255. This works because the Z80 is little-endian.

The return parameter must be initialised before being passed, otherwise BASIC will throw an Improper argument error. In the below image, I am printing (with the shortcut ? since I've golfed the demonstration too!) the return values immediately before and after the call to show the value changing. I'm using the value &FFFF because that is the binary representation of -1 for a signed integer. This demonstrates that the 5-byte program correctly writes both bytes, whereas the 2-byte program only writes the low byte and assumes that the high byte is already &00.

enter image description here

CJ Dennis

Posted 2018-04-10T03:00:11.363

Reputation: 4 104

So how does the calling convention you're using return values? If it doesn't return them in the accumulator, or at all, then your answer is basically inventing a custom calling convention that solves the problem for you (by adding a return register, instead of passing a pointer where you can store A, if that's how you might actually do it from BASIC). Not that there's anything wrong with that, but it might be a more interesting answer to follow an existing calliing convention. – Peter Cordes – 2018-04-12T16:03:03.880

@PeterCordes Neither Amstrad BASIC nor the Z80 have the concept of scopes. All values are global and are immediately accessible until destroyed. The value of A is the same immediately after the RET instruction. The lifespan of a value in A is very short since it's the accumulator. There's no such thing as x = CALL &8000, 42. It would have to be CALL &8000, x, 42, and extra Z80 code, but then x would be 2, not 1. – CJ Dennis – 2018-04-12T22:26:36.730

I think it's fine if you include the output arg in the count, otherwise there's a 1-byte decrement instruction isn't there? I'd be interested to see a version that was actually usable from BASIC instead of being trivial. – Peter Cordes – 2018-04-12T22:32:12.367

1@PeterCordes Done! Oh, by the way, I forgot to mention not to call it with no parameters as it will overwrite its own first two instructions with &00s - NOP no-ops. Another byte can be added to make it safer, but of course without a return parameter it can't set anything. – CJ Dennis – 2018-04-13T13:44:44.340

32

Java (JDK 10), 11 bytes

a->a.length

Try it online!

Olivier Grégoire

Posted 2018-04-10T03:00:11.363

Reputation: 10 647

29Java beating Javscript is rare enouth to be noticed – The random guy – 2018-04-10T07:08:52.600

3@Therandomguy this requires something like interface x{void f(Object...a);} to be defined, and this lambda must be either stored in a variable of that interface type, or be passed to a method expecting that interface type, so I'm not really sure it counts for this challenge (even though usually java lambdas are allowed in codegolf challenges) – SamYonnou – 2018-04-10T15:40:56.437

3

@SamYonnou There is no difference with other lambdas, and as you mentioned, lambdas are fine.

– Olivier Grégoire – 2018-04-10T16:15:12.200

@OlivierGrégoire I know that lambdas are allowed, my point was that compared to JavaScript for example, you need a lot more extra code to set it up, even if you are using something like REPL and avoid the need for a main class/method (the need for the interface to be defined is what distinguishes it from JavaScript) – SamYonnou – 2018-04-11T18:09:45.673

@OlivierGrégoire: I know some Java but haven't kept up with it at all. I was interested to see Sam's comment on what boilerplate is getting swept under the rug in a Java answer that lets it actually be really short. I agree it should be allowed (even though it does give you something that you don't normally get with Java functions, right, so it's not just boilerplate reduction it's giving you arg-counting built-in). Besides that, it's still interesting as a reply to "Java beating JS". – Peter Cordes – 2018-04-12T22:36:34.537

@PeterCordes That's why the "Try it online" link in my answer exists ;-) – Olivier Grégoire – 2018-04-12T22:43:27.047

26

JavaScript, 15 bytes

[].push.bind(0)

The Array.prototype.push function takes any number of arguments, adds them to its array, and returns the size of the array. Therefore, the push function used on an empty array returns the number of arguments supplied to push.

f = [].push.bind(0)

f(10,2,65,7)
> 4

f()
> 0

The .bind(0) simply gives the push function a fixed this value so that it can be stored in a variable. In fact, the 7-byte identifier [].push can be used literally (but not assigned) without bind:

[].push(10,2,65,7)
> 4

[].push()
> 0

apsillers

Posted 2018-04-10T03:00:11.363

Reputation: 3 632

19

JavaScript (ES6), 16 bytes

(...a)=>a.length

f=
(...a)=>a.length

console.log(f())
console.log(f(1))
console.log(f(1,2))
console.log(f(1,2,3))
console.log(f(1,2,3,4))

tsh

Posted 2018-04-10T03:00:11.363

Reputation: 13 072

18

Haskell, 108 107 95 94 bytes

class T r where z::Int->r
instance T Int where z=id
instance T r=>T(a->r)where z n _=z$n+1
z 0

Try it online!

This was surprisingly hard to get working, but I had fun trying to find out how to implement something that's trivial in imperative languages.

user9549915

Posted 2018-04-10T03:00:11.363

Reputation: 401

Damn, you beat me to it. f is optional if you say z 0 is the function without the binding, so main = print $ ((z 0) pi 0 () [] :: Int) works. – Angs – 2018-04-10T07:40:55.660

And by that I mean that the types work when used as an anonymous function so you can indeed remove everything from the last two rows except z 0 – Angs – 2018-04-10T07:55:20.077

Nice, thanks! Turns out I was doing something wrong when I was testing the anonymous function. Tried your example and it worked just fine. – user9549915 – 2018-04-10T08:07:14.780

I guess the ::Int should be counted in the byte count, since the type of the answer has to be declared sooner or later, like in main = print $ ((z 0 :: Double -> Integer -> () -> [a] -> (Int->Int->Int) -> IO () -> Int) pi 0 () [] (+) main). I also think that this works only during compile time so something like foldl(\a b->a b) (z 0) $ [1..5])::Int can't work. Either way, this is great stuff. – Angs – 2018-04-10T11:04:21.730

Very nice! Btw. you can remove a superfluous space between T(a->r) and where. – ბიმო – 2018-04-10T12:37:09.763

2s/imperative/non-curry/ – user202729 – 2018-04-10T15:51:46.620

@Angs I've been going back and forth on the signature byte count. I feel like it should be included too, but on the other hand, it's +5 bytes per call rather than a constant amount, so assuming it's only used once seems arbitrary. It seemed more consistent to take the signature as a requirement for calling the function and exclude it from the byte count. – user9549915 – 2018-04-10T19:48:54.990

The version in your tio link has an extra space in the second instance, that is not in your answer nor necessary. – Post Rock Garf Hunter – 2019-12-26T13:28:12.570

16

Python 3, 15 bytes

lambda*a:len(a)

Try it online!

Leaky Nun

Posted 2018-04-10T03:00:11.363

Reputation: 45 011

4Also, Python 2 :) – Chas Brown – 2018-04-10T03:09:48.967

It's not at all surprising that this was the first answer. ;) – jpmc26 – 2018-04-14T03:38:22.537

12

Zsh, 7 5 bytes

<<<$#

Try it online!

Pavel

Posted 2018-04-10T03:00:11.363

Reputation: 8 585

Though it should probably be wrapped: f(){ echo $#; } – muru – 2018-04-10T07:39:23.807

8@muru That looks fine as a full program to me. – Neil – 2018-04-10T08:14:31.387

Although, I see now that the OP only wants a function... – Neil – 2018-04-10T15:50:15.090

2@Neil shell scripts act exactly like functions. OP doesn't clear on what a function is, I claim my submission is just a function saved to the disk. – Pavel – 2018-04-10T17:28:51.517

9

Brain-Flak, 6 bytes

My first Brain-Flak solution worthy posting, I guess it's the right tool for this job:

([]<>)

Try it online!

Explanation

When executing a Brain-Flak program, initially the left stack contains all arguments. From there it's simply a matter of:

(      -- push the following..
 []    --   height of the stack (ie. # of arguments)
   <>  -- ..to the other stack  (toggles to the other stack)
)      --
       -- the right stack now contains the # of arguments which
       -- gets printed implicitly

ბიმო

Posted 2018-04-10T03:00:11.363

Reputation: 15 345

7

Wolfram Language (Mathematica), 11 bytes

Tr[1^{##}]&

Try it online!

Suggested by JungHwan Min. Some restrictions (input must be rectangular) but we are not required to handle arbitrary input.

11 bytes

Length@!##&

Try it online!

Another 11 byte solution suggested by Martin Ender. This seems to error when there isn't one input but it still returns the correct value in all cases.

12 bytes

Length@{##}&

Try it online!

My original solution.

In Mathematica ## stands for a variadic number of arguments in a function. { and } wraps them in a list and Length@ takes the length of this list. & at the end turns this into an actual function.

dylnan

Posted 2018-04-10T03:00:11.363

Reputation: 4 993

7

C++14 (gcc), 34 bytes

As generic variadic lambda function (C++14 required):

[](auto...p){return sizeof...(p);}

Try it online!

Previous (incorrect) answer: 32 bytes

It was missing the template<class...T> and (p)

int f(T...p){return sizeof...p;}

Bierpfurz

Posted 2018-04-10T03:00:11.363

Reputation: 121

6C++14, C++11 has no generic lambdas. – Quentin – 2018-04-10T12:55:54.570

1

You could add the permissive flag to be able to remove the parenthesis around p (and -w to turn off the warning).

– nwp – 2018-04-10T16:00:37.613

@nwp: wouldn't -fpermissive cost you the 12 bytes for that option, though? If it's not standard ISO C++ or GNU C++. – Peter Cordes – 2018-04-12T16:05:17.423

@PeterCordes It probably does and is intended to avoid having a trivial 0-byte solution for everything by passing the program via command line. I just didn't think about that here because it seems to not be abusive. – nwp – 2018-04-12T16:16:00.060

@Quentin fixed -> C++14 – Bierpfurz – 2018-04-15T07:15:46.760

7

R, 30 bytes

function(...)length(list(...))

Try it online!

JAD

Posted 2018-04-10T03:00:11.363

Reputation: 2 898

1function(...)nargs() is 20 bytes, but using length(...) was my initial approach until I googled a nargs-like function. – Giuseppe – 2018-04-10T12:15:11.553

@Giuseppe hmm, I tried converting the list(...) to a logical so sum() could be used, but that's tricky :/ – JAD – 2018-04-10T12:23:32.100

sum(!!c(...)) also fails on the empty test case – JAD – 2018-04-10T12:25:45.560

and sum(1|c(...)) doesn't cope well with characters – JAD – 2018-04-10T12:26:52.053

I've commented to see if taking a single data type is allowed, to try and get sum(1|c(...)) to work. – Giuseppe – 2018-04-10T13:36:08.873

@Giuseppe I doubt it tbh, it'd kinda be against the spirit of the challenge – JAD – 2018-04-10T15:59:03.070

But this counts the total number of elements of arrays passed in, not the number of arrays. I don't know if it's possible using combine in place of list here. – RoryT – 2018-04-11T08:33:32.877

@RoryT hmmmm, you're right. I'm reverting it to list – JAD – 2018-04-11T08:34:51.923

Also, I think c stands for concatenate :) – JAD – 2018-04-11T08:35:14.657

1Haha, don't try and bait me into that argument ;) – RoryT – 2018-04-11T08:43:59.907

1@RoryT oh actually, R docs say combine. Nevermind :D – JAD – 2018-04-11T08:44:40.220

2...length() does the same thing as length(list(...)) – Giuseppe – 2018-04-17T16:42:19.607

@Giuseppe just curious to know why no one ever answered with nargs as you suggest? Seems like the natural answer. – JayCe – 2018-06-08T01:19:54.953

@JayCe eh, JAD has really only been semi-active on PPCG for the last few months, so I am not particularly surprised. You're more than welcome to post it yourself. – Giuseppe – 2018-06-08T13:42:54.333

@Giuseppe ty just did that. – JayCe – 2018-06-08T14:25:44.547

7

Bash, 12 bytes (thanks to paxdiablo for saving 4)

n()(echo $#)

Copy and paste at a bash prompt. Then run the n function from the prompt:

$ n
0
$ n 46 gr 3443 dad
4
$ n 4fwj23 wrw jdwj 00998 34 eyt q3 vg wq j qw
11

Wastrel

Posted 2018-04-10T03:00:11.363

Reputation: 71

2Welcome to PPCG! – Martin Ender – 2018-04-10T18:52:16.310

can you just say it is a script "./n" and not a function? then it is just: echo $#, 7 bytes. (will be then any shell you use to launch the "./n" script with. ie, you run bash? then when you: ./n arg1 ... argn it will be interpreted by bash.) – Olivier Dulac – 2018-04-13T13:04:50.113

@Olivier Dulac The challenge clearly says a function. – Wastrel – 2018-04-13T17:04:03.973

5

Ruby, 12 bytes

->*a{a.size}

Try it online!

*a is a splat of the arguments, making a consume all arguments passed to the Proc. a.size obtains its size.

Conor O'Brien

Posted 2018-04-10T03:00:11.363

Reputation: 36 228

5

Perl 6, 5 bytes

Thanks @Joshua for -5 bytes

{+@_}

Try it online!

ASCII-only

Posted 2018-04-10T03:00:11.363

Reputation: 4 687

You could just do {+@_} – Joshua – 2018-04-10T04:44:41.653

@Joshua >_> true, thanks – ASCII-only – 2018-04-10T04:48:03.220

You can remove the sub in Perl 6 (not in Perl 5, though). – nwellnhof – 2018-04-10T17:47:43.600

@nwellnhof Oh, TIL. Perl 6 is so different from Perl 5 >_> – ASCII-only – 2018-04-11T00:44:42.297

5

Octave, 9 bytes

@()nargin

Try it online!

Anonymous function taking any number of arguments (and silently discarding the lot), and outputs the number of arguments through the built-in nargin. This does not work in MATLAB, where you would need varargin to allow for arbitrary many arguments.

Sanchises

Posted 2018-04-10T03:00:11.363

Reputation: 8 530

4

Perl 5, 9 bytes

sub{~~@_}

Try it online!

Chris

Posted 2018-04-10T03:00:11.363

Reputation: 1 313

A quick sitewide search of answers seems to indicate that you can leave out the sub – ASCII-only – 2018-04-10T05:53:58.380

2Protip: TIO let's you copy in PPCG post format (ESC, S, G) – ASCII-only – 2018-04-10T05:55:03.450

@ASCII-only Oh nice, thanks! :) As for leaving out the sub, I don't think so. It's not a function without it. – Chris – 2018-04-10T05:59:26.260

@ASCII-only I'd consider answers without sub invalid since the result isn't something you can call or assign to a variable – Ton Hospel – 2018-04-10T05:59:46.530

4

Dodos, 32 31 bytes

f
	dot i f dab
i
	
	dip dot dab

Try it online!

Uses Dennis' increment function.

Explanation

f                     # definition of f - target function
        dot i f dab   # sum of j(f(all args but first)). recurses until it has 0 args
i                     # definition of i - returns (arg, 1) given 1 arg
                      # arg
        dip dot dab   # 1 (dot dab on list of length 1 returns 0, dip returns |0 - 1|)

Alternatively, 32 bytes without recursion in target function (thanks @Leo)

	dot i
i
	dip dot dab dot
	i dab

Try it online!

Explanation

        dot i             # anonymous function: sum of i(args)
                          # here this becomes implicit main
i                         # definition of i - returns a list with all arguments replaced with 1
        dip dot dab dot   # 1 (dab dot returns empty list, dot returns 0, dip returns |0 - 1|
        i dab             # list concatenated with i(all args but first)

ASCII-only

Posted 2018-04-10T03:00:11.363

Reputation: 4 687

Here's another same-length solution Try it online! I can't seem to understand why yours works though, could you add an explanation please?

– Leo – 2018-04-10T04:47:49.637

Hey, you added an explanation to my solution! I wanted one for yours, I know how mine works xD – Leo – 2018-04-10T05:34:37.990

1@Leo sorry for late reply, idek what I'm doing, just copied Dennis' function, will try to understand asap. I had no idea how dodos works so I figured out what yours did first – ASCII-only – 2018-04-10T05:36:21.383

No worries, it was just a funny situation :) – Leo – 2018-04-10T05:38:13.187

@Leo ok so does my explanation make sense? (note: I'm on mobile so feel free to edit it to make it better lol) – ASCII-only – 2018-04-10T05:46:53.487

Yes it does, thank you! – Leo – 2018-04-10T06:01:41.810

Is it a typo that i defines j? – NoOneIsHere – 2018-04-14T11:27:28.720

@NoOneIsHere Oops, fixed, thanks – ASCII-only – 2018-04-15T01:06:04.187

4

PHP, 34 bytes

function(...$a){return count($a);}

Jarno

Posted 2018-04-10T03:00:11.363

Reputation: 41

Nice one! The alternative, for PHP 5.6 and older, is function(){return func_num_args();} (35 bytes, posted below). – Ismael Miguel – 2018-04-10T14:16:57.473

@IsmaelMiguel This one also works in PHP 5.6.

– axiac – 2018-04-10T14:56:33.953

1

You should mention this works only in PHP 5.6 and newer.

– axiac – 2018-04-10T14:57:03.890

@axiac You're right, my bad. Was thinking about PHP5.5 – Ismael Miguel – 2018-04-10T15:12:32.623

4

C# .NET, 11 bytes

a=>a.Length

Try it online.

Explanation:

In C# .NET object is used for multi-type arguments, allowing one to pass integers, strings, characters, etc. as possible inputs. For example:

// Can be called like: `F(2)`, `F("test")`, `F('a')`, etc.
void F(object arg){ ... }

C# .NET can also have a fixed size of optional arguments. For example:

// Can be called like: `F()`, `F(2)`, `F("test")`, `F('a')`, etc.
void F(object arg = null){ ... }

And there are also varargs, which is an undefined amount of optional arguments (which is what I've used in this answer). For example:

// Can be called like: `F()`, `F(2)`, `F(2, "test", 'a')`, etc.
void F(params object[] args){ ... }

Usually lambdas are created like this:

System.Func<object[], int> F f = a=>a.Length;
// A call like `f(new object[]{2, "test", 'a'))` will return 3 (size of the input array)

But unfortunately System.Func doesn't support params varargs, so I'll have to create a delegate instead:

delegate int F(params object[] args);
F f = a=>a.Length;
// A call like `f()` will return 0, and `f(2, "test", 'a')` will return 3

Which is my answer for this challenge, and can be found in the linked TIO test code.


The only limitation is that inputting an actual object[] like f(new object[]{1,2,3}) will result in 3 instead of 1. f(new int[]{1,2,3}) will still result in 1, because it interprets the int[] as a single object. To have the object[] parameter be interpret as a single object as well it can be casted to an object like this: f((object)new object[]{1,2,3}).

Kevin Cruijssen

Posted 2018-04-10T03:00:11.363

Reputation: 67 575

I have to say, if there were ever an answer that made me support including lambda-related boilerplate in C# answers it would be this one... but it is definitely a valid solution. – Kamil Drakari – 2018-04-10T15:23:43.040

@KamilDrakari Maybe it indeed wasn't very clear what I did without opening the TIO-link, so I've added an explanation. – Kevin Cruijssen – 2018-04-11T09:25:05.193

Fails when passed a single array as argument. Ie. f(new object[]{1, 2, 3}) – Taemyr – 2018-04-11T14:17:26.480

1@Taemyr I tried finding a solution, but unfortunately there is none for C# .NET, except for casting any object[] parameters to object, like this: f((object)new object[]{1,2,3});. There is no way to differentiate between f(new object[]{1,2,3}); and f(1,2,3); as far as I could find. – Kevin Cruijssen – 2018-04-11T14:58:16.090

1this handles array parameters correctly for a huge penalty of bytes. There might be a more concise structure that can handle it, but it works in my testing. – Kamil Drakari – 2018-04-11T15:10:45.903

1@KamilDrakari Hmm, but it fails for f(1, new object[]{1,2,3}) again though. Not sure if a solution for this behavior can be found. – Kevin Cruijssen – 2018-04-11T15:43:14.877

Well... I don't know if this was missed or has simply been changed, but reading the Challenge again it appears that both "Supporting only up to a maximum number of inputs" and "Supporting only specific data types" are allowed, so the solution is valid as-is with the simple note "supports data types other than object[]", though some other use of those allowances could save characters. – Kamil Drakari – 2018-04-11T16:17:19.967

There may be some benefits to using the dynamic type over object => delegate int F(params dynamic[] a);. This saves you from having to type cast the args. – dana – 2018-12-15T17:31:21.903

3

C++, 72 bytes

int f(){return 0;}template<class...P>int f(int,P...p){return f(p...)+1;}

Saves bytes by only working with ints.

bridgerrholt

Posted 2018-04-10T03:00:11.363

Reputation: 51

You can use sizeof.... – L. F. – 2019-07-23T04:02:54.310

3

Rust, 57 bytes

macro_rules!f{()=>{0};($($x:expr),+)=>{[$($x),+].len()};}

Explanation:

macro_rules! f {         // define a macro called f
    () => {0};           // when called without arguments, expand to 0
    ($($x:expr),+) => {  // when called with 1 or more comma seperated arguments
        [                // rust uses [a, b, c] to make an array
            $($x),+      // expand to the arguments seperated with a comma
        ]                
        .len()           // take the length of that.
    };
}

Test:

fn main() {
    println!("{:?}", f!());                // prints 0
    println!("{:?}", f!(4));               // prints 1
    println!("{:?}", f!(5, 2));            // prints 2
    // works with anything, as long as you dont mix things
    println!("{}", f!("", "a", "hello"));  // prints 3
}

corvus_192

Posted 2018-04-10T03:00:11.363

Reputation: 1 889

2

PHP, 35 bytes

function(){return func_num_args();}

manual entry

Titus

Posted 2018-04-10T03:00:11.363

Reputation: 13 814

2

Common Lisp, 28 bytes

(defun f(&rest a)(length a))

Try it online!

ASCII-only

Posted 2018-04-10T03:00:11.363

Reputation: 4 687

2

Add++, 3 bytes

L,L

Try it online!

caird coinheringaahing

Posted 2018-04-10T03:00:11.363

Reputation: 13 702

2

Batch, 50 49 bytes

set n=0
for %%a in (%*)do set/an+=1
exit/b%n%

No builtin in Batch, so we have to go old-school. Saved 1 byte thanks to @IsmaelMiguel. Outputs via exit code, or save 3 bytes if output via global variable is valid. Example of use in a full program:

@echo off
call:c %*
echo %ERRORLEVEL%
exit/b
:c
set n=0
for %%a in (%*)do set/an+=1
exit/b%n%

Neil

Posted 2018-04-10T03:00:11.363

Reputation: 95 035

I believe that this answer is answer goes (somewhat) against the rules. Batch has something somewhat close to functions. You can do something similar to :a|set r=0&for %%a in (%*)do set/ar+=1 (| = windows-style newline). This solution is 38 bytes. To execute it, do call :a <args> with a goto :eof before the function, being the value available inside the variable r. If you want to keep your solution, remove the /a on the first set, and remove those @. – Ismael Miguel – 2018-04-11T09:39:56.190

@IsmaelMiguel Like this? (Note: I didn't include the function name in the byte count, but I did include the function return, which seems reasonable, as there needs to be one somewhere.) – Neil – 2018-04-11T11:32:06.277

Yes, that's exactly it. Nice catch with the exit code! I was surprised to see that exitcodes can be larger than 255. An example is the list provided by Symantec: https://www.symantec.com/connect/articles/windows-system-error-codes-exit-codes-description

– Ismael Miguel – 2018-04-11T12:36:20.830

2

PHP, 11 bytes

<?=$argc-1;

Try it online: 1 input | 3 inputs

Shaggy

Posted 2018-04-10T03:00:11.363

Reputation: 24 623

I'm not so sure about this one (and it's validity) since it is the count of arguments passed to call PHP. – Ismael Miguel – 2018-04-10T14:20:09.620

@IsmaelMiguel, see this consensus.

– Shaggy – 2018-04-10T14:31:08.933

1The question explicitly requires a function that returns the number, does not display it: "...write a function that takes a variable number of arguments and returns the number of arguments." – axiac – 2018-04-10T14:59:20.770

1Re-quoting the question: "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.". Your code doesn't contain functions. – Ismael Miguel – 2018-04-10T15:11:28.407

@IsmaelMiguel, if that were indeed the case then many other solutions would also be invalidated. The norm is to allow solutions to be programmes or functions. – Shaggy – 2018-04-11T09:01:47.073

I believe that all (or, at least, most of) the programming languages that do that do not have a very specific concept of a function. Batch, for example, has something that looks and (somewhat) works like a function. But is just a label pointing to some code. And in that case, I've already left my comment there. – Ismael Miguel – 2018-04-11T09:41:40.330

2

x86 32-bit (i386) machine code function, 13 bytes

Calling convention: i386 System V (stack args), with a NULL pointer as a sentinel / terminator for the end-of-arg-list. (Clobbers EDI, otherwise complies with SysV).

C (and asm) don't pass type info to variadic functions, so the OP's description of passing integers or arrays with no explicit type info could only be implemented in a convention that passed some kind of struct / class object (or pointers to such), not bare integers on the stack. So I decided to assume that all the args were non-NULL pointers, and the caller passes a NULL terminator.

A NULL-terminated pointer list of args is actually used in C for functions like POSIX execl(3): int execl(const char *path, const char *arg, ... /* (char *) NULL */);

C doesn't allow int foo(...); prototypes with no fixed arg, but int foo(); means the same thing: args unspecified. (Unlike in C++ where it means int foo(void)). In any case, this is an asm answer. Coaxing a C compiler to call this function directly is interesting but not required.

nasm -felf32 -l/dev/stdout arg-count.asm with some comment lines removed.

24                       global argcount_pointer_loop
25                       argcount_pointer_loop:
26                               .entry:
28 00000000 31C0             xor   eax, eax  ; search pattern = NULL
29 00000002 99               cdq             ; counter = 0
30 00000003 89E7             mov   edi, esp
31                       ;    scasd           ; edi+=4; skip retaddr
32                       .scan_args:
33 00000005 42               inc   edx
34 00000006 AF               scasd            ; cmp eax,[edi] / edi+=4
35 00000007 75FC             jne  .scan_args
36                       ;    dec   edx       ; correct for overshoot: don't count terminator
37                       ;    xchg  eax,edx
38 00000009 8D42FE           lea   eax, [edx-2]    ; terminator + ret addr
40 0000000C C3               ret

size = 0D               db $ - .entry

The question shows that the function must be able to return 0, and I decided to follow that requirement by not including the terminating NULL pointer in the arg count. This does cost 1 byte, though. (For the 12-byte version, remove the LEA and uncomment the scasd outside the loop and the xchg, but not the dec edx. I used LEA because it costs the same as those other three instructions put together, but is more efficient, so the function is fewer uops.)

C caller for testing:

Built with:

nasm -felf32 -l /dev/stdout arg-count.asm | cut -b -28,$((28+12))- &&
 gcc -Wall -O3 -g -std=gnu11 -m32 -fcall-used-edi arg-count.c arg-count.o -o ac &&
 ./ac

-fcall-used-edi is required even at -O0 to tell gcc to assume that functions clobber edi without saving/restoring it, because I used so many calls in one C statement (the printf call) that even -O0 was using EDI. It appears to be safe for gcc's main to clobber EDI from its own caller (in CRT code), on Linux with glibc, but otherwise it's totally bogus to mix/match code compiled with different -fcall-used-reg. There's no __attribute__ version of it to let us declare the asm functions with custom calling conventions different from the usual.

#include <stdio.h>

int argcount_rep_scas();       // not (...): ISO C requires at least one fixed arg
int argcount_pointer_loop();   // if you declare args at all
int argcount_loopne();

#define TEST(...) printf("count=%d = %d = %d   (scasd/jne) | (rep scas) | (scas/loopne)\n", \
        argcount_pointer_loop(__VA_ARGS__), argcount_rep_scas(__VA_ARGS__), \
        argcount_loopne(__VA_ARGS__))

int main(void) {
    TEST("abc", 0);
    TEST(1, 1, 1, 1, 1, 1, 1, 0);
    TEST(0);
}

Two other versions also came in at 13 bytes: this one based on loopne returns a value that's too high by 1.

45                       global argcount_loopne
46                       argcount_loopne:
47                           .entry:
49 00000010 31C0             xor   eax, eax  ; search pattern = NULL
50 00000012 31C9             xor   ecx, ecx  ; counter = 0
51 00000014 89E7             mov   edi, esp
52 00000016 AF               scasd           ; edi+=4; skip retaddr
53                       .scan_args:
54 00000017 AF               scasd
55 00000018 E0FD             loopne  .scan_args
56 0000001A 29C8             sub   eax, ecx
58 0000001C C3               ret

size = 0D = 13 bytes               db $ - .entry

This version uses rep scasd instead of a loop, but takes the arg count modulo 256. (Or capped at 256 if the upper bytes of ecx are 0 on entry!)

63                       ; return int8_t maybe?
64                       global argcount_rep_scas
65                       argcount_rep_scas:
66                               .entry:
67 00000020 31C0             xor   eax, eax
68                           ;    lea   ecx, [eax-1]
69 00000022 B1FF             mov   cl, -1
70 00000024 89E7             mov   edi, esp
71                       ;    scasd              ; skip retaddr
72 00000026 F2AF             repne scasd        ; ecx = -len - 2 (including retaddr)
73 00000028 B0FD             mov   al, -3
74 0000002A 28C8             sub   al, cl       ; eax = -3 +len + 2
75                       ;    dec   eax
76                       ;    dec   eax
77 0000002C C3               ret

size =  0D = 13 bytes         db $ - .entry

Amusingly, yet another version based on inc eax / pop edx / test edx,edx / jnz came in at 13 bytes. It's a callee-pops convention, which is never used by C implementations for variadic functions. (I popped the ret addr into ecx, and jmp ecx instead of ret. (Or push/ret to not break the return-address predictor stack).

Peter Cordes

Posted 2018-04-10T03:00:11.363

Reputation: 2 810

2

R, 20 bytes

function(...)nargs()

Try it online!

R has a function just for that.

JayCe

Posted 2018-04-10T03:00:11.363

Reputation: 2 655

1

JavaScript, 35 bytes

f=
function(){return arguments.length}

console.log(f(2,5,4))

l4m2

Posted 2018-04-10T03:00:11.363

Reputation: 5 985

1

Cauliflower, 16 bytes

(\((@a))(len@a))

Try it online!

ASCII-only

Posted 2018-04-10T03:00:11.363

Reputation: 4 687

1

Actually, 2 bytes

` 

Try it online!

Note: this is a grave and a space

ASCII-only

Posted 2018-04-10T03:00:11.363

Reputation: 4 687

1

Japt, 2 bytes

Nl

I suspect the answer will be similar in many golfing languages, take all of the inputs as an array and return its length.

Try it online!

Nit

Posted 2018-04-10T03:00:11.363

Reputation: 2 667

1Beat me to it. If I haven't done so already: Welcome to Japt! :) – Shaggy – 2018-04-10T08:10:11.587

1

Kotlin, 26 bytes

Defines function a with a vararg parameter x: Any. Thus, the arguments passed can be anything but null.

fun a(vararg x:Any)=x.size

Try It Online!

snail_

Posted 2018-04-10T03:00:11.363

Reputation: 1 982

1

Clojure, 11 bytes

#(count %&)

Try it online!

Uriel

Posted 2018-04-10T03:00:11.363

Reputation: 11 708

1

Lua, 11 bytes

print(#arg)

Try it online: 1 input | 3 inputs

Shaggy

Posted 2018-04-10T03:00:11.363

Reputation: 24 623

Note that as of Lua 5.1, arg only refers to the parameters passed when evaluating the script and does not work when defining a function. – Lucien Greathouse – 2018-04-12T06:26:33.013

1

Go, 44 30 28 bytes

-2 bytes thanks to BMO

My first code golf attempt.

func(a...int){print(len(a))}

Try it online (outputs to Debug-window instead of STDOUT).

Pizza lord

Posted 2018-04-10T03:00:11.363

Reputation: 119

1

Welcome to the site! I've edited your post to match the general answer format we use here. Is it possible for you to edit in a link to somewhere where others can test your code, such as Try It Online!

– caird coinheringaahing – 2018-04-10T12:15:46.853

added a link to a modified workign example, sadly go only runs main packages – Pizza lord – 2018-04-10T12:26:21.513

Welcome to PPCG! I noticed you had your TIO-link in your header. So I've put it below it, and fixed the header-link. Enjoy your stay! – Kevin Cruijssen – 2018-04-10T13:49:27.460

1

PowerShell 3, 25 bytes

function a(){$args.Count}

Usage:

a 1 2 ...

Console output for "a 1 2 3"

PS: C:\> a 1 2 3
3

Pretty self explanatory. Powershell stores all unspecified args in the $args list, so we just grab a count of it. Since the language implicitly writes values to the console, the act of finding the count will print to the console without needing a Write-Host or Write-Output.

Edit: Mistyped; should have been 25 bytes (typed 35).

Arkitekt

Posted 2018-04-10T03:00:11.363

Reputation: 131

1You can use filter instead of function. Or just raw scriptblock: .{$args.Count} 1 2 3 4 5 – beatcracker – 2018-04-10T18:56:06.340

Good idea. I chose "function" to fulfill the challenge text:

Using your language of choice, write a function that takes a variable number of arguments...

I guess it depends on how loose the definition of "function" is in this case. – Arkitekt – 2018-04-10T20:26:28.600

1

Stax, 4 bytes

{L%}

Run and debug it at staxlang.xyz!

Simple. Listifies the entire stack and all input, and returns the resulting length. No thought went into this answer.

Works without the closing brace, but I think that that makes it an incomplete "function" (block).

Khuldraeseth na'Barya

Posted 2018-04-10T03:00:11.363

Reputation: 2 608

I don't think I realized that it would be a legal program without the closing brace. Interesting! – recursive – 2018-04-10T17:37:16.577

@recursive I was as surprised as you. Though interesting, this sadly seems useless at this point (as far as I can tell). – Khuldraeseth na'Barya – 2018-04-10T19:03:24.000

Yes, it doesn't seem useful for general golfing, which is probably why I didn't make it do anything in particular. An unterminated block is necessarily at the end of the program, so there's nothing to do but execute it. You could achieve the same result by "inlining" the contents of the block. Maybe some day I could make it do something else. Hm... – recursive – 2018-04-10T19:05:34.937

1

Vim, 10 bytes

:ec argc()

Where "an argument" is a filename for Vim to edit. Hopefully this counts.

ZirconiumX

Posted 2018-04-10T03:00:11.363

Reputation: 11

1

Avail, 32 characters.

Method"f(«_‡,»)"is[t:tuple||t|];

Avail's a little different. Any particular function has fixed arity, so the nearest approximation is a multi-method taking a polyadic argument (shown with spaces)...

Method "f(«_‡,»)" is [t : tuple | |t|];
Assert f(10,20,30) = 3;

The guillemets say expect multiple arguments (the underscore), separated by commas (the comma after the double-dagger). The "f", "(", and ")" (and ",") are actual keywords of this method. The guillemet mechanism is supported by the compiler, which assembles instructions at call sites (like the Assert statement on the second line) to assemble arguments into a tuple, mostly similar to Java. However, Avail also supports multiple repeated arguments, nested repetitions, strong heterogeneously typed arguments, and a ton more.

In the general spirit of code golf,

Method "g(«x‡,»#)" is [w : whole number | w];
Assert g(x,x,x) = 3;

The # after the close-guillemet arranges to pass the number of repetitions of the preceding group, rather than the actual tuple. However, it's pointless to throw away actual arguments, so they're forbidden in such a group. Only constant tokens are allowed, namely "x" in this case, as reflected in the example assertion.

Mark van Gulik

Posted 2018-04-10T03:00:11.363

Reputation: 11

Welcome to PPCG! Since this is code golf, could you include the byte count of the code that is necessary to define f (ideally with unnecessary whitespace removed, if any of it is unnecessary). A link to an implementation and/or specification of Avail would be great too. :) – Martin Ender – 2018-04-10T19:29:45.317

Updated. Thanks for the tip! – Mark van Gulik – 2018-04-10T20:26:24.063

There's a summary of the message pattern language (including the «p1‡,p2» format) in the quick start, and the |_| size method is documented in the stacks here.

– tdhsmith – 2018-04-10T21:03:13.003

1

AutoHotkey, 33 bytes

f(p*){
n+=p.MaxIndex()
return n
}

The asterisk * defines the parameter p as a variadic parameter.
MaxIndex() returns the highest numeric index which, in this case, is the parameter count.
By starting with nothing and adding the MaxIndex, you get a 0 for empty calls.

Here's an example of it in a full program:

MsgBox % f()
MsgBox % f(1)
MsgBox % f([1, 2, 3])
MsgBox % f(1, 10)
MsgBox % f(1, "a")

Exit

f(p*){
n+=p.MaxIndex()
return n
}

The returns as shown in the message box are (in order) 0,1,1,2,2.


AutoHotkey, 8 bytes

If it is allowable to write an entire program that returns the number of parameters passed to it, the result is much shorter:

Send %0%

Engineer Toast

Posted 2018-04-10T03:00:11.363

Reputation: 5 769

I don't know this language, but won't something like return p.MaxIndex() work? – Ørjan Johansen – 2018-04-12T18:06:54.307

@ØrjanJohansen Unfortunately, that would return an empty value when no parameters are passed instead of the desired value 0. – Engineer Toast – 2018-04-12T18:09:38.477

Hm. What about return 0+p.MaxIndex()? – Ørjan Johansen – 2018-04-12T18:13:33.507

@ØrjanJohansen Also an empty value. AHK is pretty finnicky about doing math (or any other functions) inside of another function. It's not a very good golfing language. – Engineer Toast – 2018-04-12T18:16:18.493

1

Röda, 15 bytes

main a...{[#a]}

Try it online!

a... indicates that the program takes in a variable number of arguments

[ ] prints the following

  • #a the length of variable a

user41805

Posted 2018-04-10T03:00:11.363

Reputation: 16 320

1

x86-64 machine code, 5 bytes (program for Linux, exit status = ret value)

ia32 (i386) machine code, 4 bytes

This program does sys_exit(argc).

It works for the x86-64 System V ABI, where the stack on process entry has argc followed by argv[0], argv[1], ... NULL, envp[0], ..., NULL. (Or the i386 SysV ABI, where the stack layout is the same, but in 4-byte elements).

nasm -felf64 -l /dev/stdout arg-count.asm listing output:

 1                                  global _start
 2                                  _start:
 3 00000000 5F                          pop rdi
 4 00000001 B03C                        mov al, 60     ; __NR_exit
 5 00000003 0F05                        syscall

Most registers (including rax) are zeroed by the kernel on entry to user-space. To we can set rax=60 with just a mov al in a static executable where no dynamic linker code ran first.

Assemble + link into a static executable with
yasm -felf64 arg-count.asm && ld -o arg-count arg-count.o


   32-bit version: nasm -felf32 -l /dev/stdout arg-count.asm 
 1                                  global _start
 2                                  _start:
 3 00000000 5B                          pop ebx
 4 00000001 40                          inc eax       ; __NR_exit = 1
 5 00000002 CD80                        int 0x80

yasm -felf32 arg-count32.asm &&
ld -melf_i386 -o arg-count32 arg-count32.o

32-bit __NR_exit is 1, so the constant only takes a 1-byte inc (the kernel still zeros registers).


Note that argc includes the first arg passed by the shell which by convention is the name of the executable, but doesn't have to be. execve doesn't care if you exec a process with argv[0] being something other than the executable filename. It's a real arg, and some programs actually use it to figure out how they were invoked (useful for multiple hardlinks to one executable with different behaviours, like busybox can be ls or mv depending on argv[0])

$ ./arg-count ; echo $?     # by convention, program name is passed as a first arg
1
$ ./arg-count a b c d; echo $?
5
$ ./arg-count {a..z} ; echo $?
27
$ ./arg-count $(seq 100); echo $?
101
$ ./empty-args ./arg-count ; echo $?     # runs with argc=0 / argv[0]=NULL
0

(empty-args is a wrapper program that calls execve(argv[1], {NULL}, {NULL}). It is possible to "call" the program with an empty argument list, just not from bash directly.)

Note that the echo $? is just how you can see the exit status printed to the screen. It's always returned to the shell by this program, whether you print it or not. The submission is the program's machine code, not the way I run it from the shell.

Peter Cordes

Posted 2018-04-10T03:00:11.363

Reputation: 2 810

1

Spice, 23 bytes

;a;return@LEN a return;

Un-golfed explanantion

Spice has no concept of functions - the closest would be a module which are called with the format:

LOD .\module.spice (^)input result

Where the result is set to the final value of the variable return in the module. The optional ^ character passes the input as the given value rather than flattening the array across all variables in the module. So in this case we can require ^ and:

;a;return@     - declare vars
LEN a return;  - Get length of our input, a, and store in result

Slord6

Posted 2018-04-10T03:00:11.363

Reputation: 71

0

Attache, 5 bytes

{#__}

Try it online!

This is an anonymous lambda. __ simply represents the arguments passed to it, and # calculates the length.

Conor O'Brien

Posted 2018-04-10T03:00:11.363

Reputation: 36 228

0

Clojure, 11 bytes

#(count %&)

Try it online!

amalloy

Posted 2018-04-10T03:00:11.363

Reputation: 121

0

CJam, 4 bytes

{],}

This defines a code block (CJam's analogous construct to a function) that takes all the stack contents as inputs.

Try it online!

Explanation

{  }    e# Define block
 ]      e# Concatenate all stack into a list
  ,     e# Length

Luis Mendo

Posted 2018-04-10T03:00:11.363

Reputation: 87 464

0

Go, 31 bytes

func a(b ...int){print(len(b))}

Only works with integers to save space.

Try it here

Kristoffer Sall-Storgaard

Posted 2018-04-10T03:00:11.363

Reputation: 489

0

Tcl, 27 bytes

proc F args {llength $args}

Try it online!

sergiol

Posted 2018-04-10T03:00:11.363

Reputation: 3 055

0

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)

Ismael Miguel

Posted 2018-04-10T03:00:11.363

Reputation: 6 797

0

Julia 0.6, 16 bytes

f(x...)=endof(x)

Try it online!

gggg

Posted 2018-04-10T03:00:11.363

Reputation: 1 715

0

Quantum64

Posted 2018-04-10T03:00:11.363

Reputation: 371

0

Swift, 37 bytes

func r(s:Any...)->Int{return s.count}

Try it online!

Tamás Sengel

Posted 2018-04-10T03:00:11.363

Reputation: 211

0

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!

mbomb007

Posted 2018-04-10T03:00:11.363

Reputation: 21 944

49? – ASCII-only – 2018-06-09T05:35:34.333

@ASCII-only Oh, I forgot that's how values used to be returned in old VB syntax. That should work. – mbomb007 – 2018-06-09T19:28:21.433

0

REXX, 12 bytes

return arg()

arg without arguments returns the number of arguments.

idrougge

Posted 2018-04-10T03:00:11.363

Reputation: 641

0

Swift, 25 characters

func f(a:Any...){a.count}

return is implicit in a trivial function body like this.

idrougge

Posted 2018-04-10T03:00:11.363

Reputation: 641

0

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.

ngenisis

Posted 2018-04-10T03:00:11.363

Reputation: 4 600

0

Pyth, 10 bytes

D[$*b$)Rlb

Try it online!

Pyth doesn't really support defining variadic functions, but it does allow embedding Python code directly into the source, and Python allows variadic functions. We can get away with just using two bytes of Python code: *b, which makes b a variadic argument, containing the list of arguments passed in. We redefine the function [, which the Pyth parser understands to be a variadic function, and then we simply return the length of b.

Note that this can be run on TIO but not the standard Pyth executor at http://pyth.herokuapp.com/, due to sandboxing limitations.

isaacg

Posted 2018-04-10T03:00:11.363

Reputation: 39 268

0

Scheme, 16 bytes

(λ a(length a))

Or defining a named function (25 bytes):

(define(f . a)(length a))

galex-713

Posted 2018-04-10T03:00:11.363

Reputation: 101

0

Yabasic, 17 bytes

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

?peek("argument")

Try it online!

Taylor Scott

Posted 2018-04-10T03:00:11.363

Reputation: 6 709

0

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

vityavv

Posted 2018-04-10T03:00:11.363

Reputation: 734

0

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

BinarySpark

Posted 2018-04-10T03:00:11.363

Reputation: 11

0

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!

Digital Trauma

Posted 2018-04-10T03:00:11.363

Reputation: 64 644

You can remove the space between f(a...) and ({char*s – ceilingcat – 2018-06-16T03:39:06.980

0

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!

ATaco

Posted 2018-04-10T03:00:11.363

Reputation: 7 898

0

C#, 32 bytes

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

Expression-bodied method with the params keyword.

Manfred Radlwimmer

Posted 2018-04-10T03:00:11.363

Reputation: 403

0

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

sonrad10

Posted 2018-04-10T03:00:11.363

Reputation: 535

1I believe you can save a few bytes by removing the "print" – pppery – 2018-08-07T03:00:10.573

0

05AB1E, 2 bytes

|g

Try it online.

Explanation:

|     # Take all new-line separated inputs as a single list
 g    # Take the length of this list

Kevin Cruijssen

Posted 2018-04-10T03:00:11.363

Reputation: 67 575

0

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.

user85052

Posted 2018-04-10T03:00:11.363

Reputation:

0

Pyth, 9 bytes

D[$*N$)lN

Try it online!

Variadic functions cannot be defined in pure Pyth, but using the raw Python override $$, it's easy. This translates to the Python program:

def list(*N):
    print(len(N))

Where [ is the function defined.

isaacg

Posted 2018-04-10T03:00:11.363

Reputation: 39 268