Sum the numbers on standard in

32

4

Consider a stream/file with one integer per line. For example:

123
5
99

Your code should output the sum of these numbers, that is 227.

The input format is strictly one integer per line. You cannot, for example, assume the input is on one line as an array of integers.

You can take input either from STDIN, in form of a filename, or a file with a name of your choice; you can choose which one. No other ways of getting input are allowed.

The input will contain at least one integer. You can assume all integers are non-negative and that their total sum is less than 232.

user9206

Posted 2017-03-23T20:36:11.547

Reputation:

2Is there a trailing newline? Is that newline optional? – Please stop being evil – 2017-03-24T06:50:06.897

9

Hi! I downvoted this challenge because it goes against our community standards for acceptable input/output formats by having a restrictive input format.

– AdmBorkBork – 2017-03-24T15:34:22.450

1@AdmBorkBork and I discussed this at length in the chat room. We have agreed to disagree :) – None – 2017-03-24T17:09:28.227

22

As the author of the things-to-avoid of cumbersome I/O and arbitrarily overriding defaults, I want to defend this challenge on those grounds. Here, the processing input is the meat of the challenge, not extra work that distracts from the main challenge. It's not "add numbers" with weird I/O requirements, it's "do this I/O" with adding as a step. Overruling the standard I/O is necessary for answers not to shortcut across the main task.

– xnor – 2017-03-24T18:58:12.487

@ais523 Ahem.

– Dennis – 2017-03-25T11:39:29.313

@Dennis: OK, I didn't think of that. Still fairly ridiculous that you have to go to those lengths, though. – None – 2017-03-25T17:09:02.347

2Why can't function input be used? – CalculatorFeline – 2017-04-09T21:02:07.807

Answers

15

05AB1E, 2 bytes

|O

Explanation:

|   Get input as array
 O  Sum

Try it online!

Okx

Posted 2017-03-23T20:36:11.547

Reputation: 15 025

7That's ridiculous :) – None – 2017-03-23T20:41:18.247

Does this read from standard in? – None – 2017-03-23T20:50:40.220

1@Lembik it does. – Okx – 2017-03-24T08:38:01.003

I believe your 2 byte answer was first. You are the winner! (Unless someone finds a 1 byte answer.) – None – 2017-03-24T13:38:59.730

4@Lembik Or a 0 byte answer.... – Comrade SparklePony – 2017-03-24T15:29:58.427

@SparklePony Write a compiler/interpreter that compiles anything to a solution to this problem - then the submission is a 0 byte program that compiles to a solution? Sorted :) – OJFord – 2017-03-25T10:47:08.987

@OJFord It would be non-competing as the language would postdate the challenge :( – Metoniem – 2017-03-27T10:36:33.493

21

Bash + coreutils, 16 bytes

xargs|tr \  +|bc

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs             # known trick to turn newlines into spaces, while adding a
                  #trailing newline when printing the result (needed for bc)
|tr \  +          # turn spaces into '+'s
|bc               # calculates the sum

You may wonder why tr \\n +|bc isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

  • if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
  • and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.

seshoumara

Posted 2017-03-23T20:36:11.547

Reputation: 2 878

1I like this. It's nice and clever. – None – 2017-03-23T21:04:13.723

Could you use tr \n + Instead without xargs? – None – 2017-03-23T23:03:20.297

1@Lembik Do you mean tr \\n +|bc? If so, then please see the updated explanation. Good question. – seshoumara – 2017-03-24T00:50:42.463

paste -s -d+|bc is 15 bytes – David Conrad – 2017-03-24T13:29:47.933

@DavidConrad The use of paste is shown in another bash answer here. No harm keeping both. Thank you for the comment anyway. – seshoumara – 2017-03-24T14:29:33.783

Does this work if there is only one line? – None – 2017-03-24T15:29:55.107

1@Lembik Didn't considered that case, but fortunately the script still works. xargs|tr \ + in this case does nothing, and bc receives the number and prints it back. – seshoumara – 2017-03-24T15:36:57.843

@seshoumara I agree. I hadn't seen that other answer yet when I commented. Cheers. – David Conrad – 2017-03-24T22:47:39.610

This is not bash specific, so should read "sh + POSIX utils" – Jens – 2017-03-27T11:56:19.397

@Jens I'm glad that it works on other shells as well, thanks for the info, but I'll keep bash in the title, since it is better known and since it's the system I tested on. – seshoumara – 2017-03-27T12:28:17.020

14

MATL, 2 bytes

Us

This expects the input in a text file called defin.

Gif or it didn't happen:

enter image description here

Or try it online! (thanks to Dennis for the set-up!)

Explanation

When a MATL program is run, if a file called defin is found (the name refers to "default input"), its contents are automatically loaded as text and pushed to the stack as a string before executing the code.

Function U evaluates the string to convert it to a column vector of numbers, and s computes the sum, which is implicitly displayed.

Luis Mendo

Posted 2017-03-23T20:36:11.547

Reputation: 87 464

13

Japt, 2 bytes

Nx

Explanation

     Implicit: parse STDIN into array of numbers, strings, and arrays
N    Get the resulting parsed array.
 x   Sum.
     Implicit: output result of last expression

Try it online!

ETHproductions

Posted 2017-03-23T20:36:11.547

Reputation: 47 880

12

Perl 6, 13 bytes

say sum lines

Try it

Explanation

  • lines() returns a list of lines from $*IN or $*ARGFILES a “magic” command-line input handle.
  • sum(…) was added to Perl 6 to allow [+] List to be optimized for Positionals that can calculate their sum without generating all of their values like 1..100000
    (I just thought sum was just too cute here to use [+] like I normally would)
  • say(…) call the .gist method on its input, and prints it with an additional newline.

Brad Gilbert b2gills

Posted 2017-03-23T20:36:11.547

Reputation: 12 713

What is it perl 5? – None – 2017-03-23T21:02:55.443

15this reads like lolcode – Bryan Boettcher – 2017-03-23T21:58:04.657

@Lembik it is clearly labeled as Perl 6, which is a sister language to Perl 5.

– Brad Gilbert b2gills – 2017-03-23T22:00:03.703

There was a typo. I meant what is it in Perl 5? – None – 2017-03-23T22:10:52.610

1Well $a+=$_ for <>;print $a works in Perl 5, but there may be a shorter way. – Brad Gilbert b2gills – 2017-03-23T22:14:34.343

It is strange a Tcl guy like me ever upvoted a Perl answer! – sergiol – 2017-06-17T11:57:24.397

12

Paste + bc, 13 bytes

paste -sd+|bc

Explanation:

paste -s        Take one line at a time from input
        d+      Joining by '+'
          |bc   Pass as expression to bc

Another shell answer!

Okx

Posted 2017-03-23T20:36:11.547

Reputation: 15 025

1Very neat and tidy. – None – 2017-03-23T21:05:07.880

Ooh, I had paste -s -d+|bc and didn't realize I could consolidate the switches. Neat! – David Conrad – 2017-03-24T13:31:14.263

10

C, 53 bytes

r;main(i){for(;~scanf("%d",&i);r+=i);printf("%d",r);}

orlp

Posted 2017-03-23T20:36:11.547

Reputation: 37 067

C showing its credentials again :) – None – 2017-03-23T21:04:49.767

2I feel like there should be a shorter way, but I don't see it :) – Digital Trauma – 2017-03-25T01:41:58.937

10

Python 3, 28 bytes

print(sum(map(int,open(0))))

Taken from this tip. I've been told this won't work on Windows.

Try it online!

Dennis

Posted 2017-03-23T20:36:11.547

Reputation: 196 637

5I learned something new! – None – 2017-03-23T22:18:39.713

9

Retina, 11 7 bytes

-4 thanks to Martin Ender

.*
$*
1

Try it online!


Convert to unary:

.*
$*

Count the number of 1s:

1

Riley

Posted 2017-03-23T20:36:11.547

Reputation: 11 345

1Interesting how Retina, as a regex based language, can do the sum in fewer bytes than the shortest bash answer posted so far. +1 – seshoumara – 2017-03-23T21:56:26.463

Is this reading from standard in? – None – 2017-03-23T22:34:00.340

2@Lembik Yes it is. – Riley – 2017-03-23T22:38:34.560

If input in unary was allowed, it'd be only one byte. – mbomb007 – 2017-03-24T14:06:46.127

@mbomb007 I already tried that in sed. – Riley – 2017-03-24T14:07:47.560

8

Brain-Flak, 20 bytes

(([]){[{}]{}([])}{})

Try it online!

Explanation

This is a golf off of a solution made by Riley in chat. His solution was:

([])({<{}>{}<([])>}{})

If your familiar with Brain-Flak this is pretty self-explanatory. It pushes the stack height and pops one value as it counts down, at the end it pushes the sum of all the runs.

It is a pretty good golf but he zeros both {} and ([]) however these will have a values that only differ by one so if instead we remove the masks and make one of the two negative they should nearly cancel out.

([])({[{}]{}([])}{})

Since they always differ by one we have the unfortunate circumstance where our answer is always off by the stack height. In order to remedy this we simply move the beginning of the push to encompass the first stack height.

(([]){[{}]{}([])}{})

Post Rock Garf Hunter

Posted 2017-03-23T20:36:11.547

Reputation: 55 382

1I thought of it as the negative pop cancels the previous height pushed (from before the loop, or the end of the previous time through), and the last height is 0 so it can be ignored. – Riley – 2017-03-23T20:51:58.673

8

Python 2, 40 bytes

import sys;print sum(map(int,sys.stdin))

orlp

Posted 2017-03-23T20:36:11.547

Reputation: 37 067

7

Pure Bash, 37 36 bytes

Thanks to @KevinCruijssen for a byte!

while read a;do((b+=a));done;echo $b

Try it online!

betseg

Posted 2017-03-23T20:36:11.547

Reputation: 8 493

3Very nice and clean. – None – 2017-03-23T21:03:17.203

I never program in Bash, but isn't it possible to remove the space between do ((? The TIO seems to work.

– Kevin Cruijssen – 2017-03-24T08:42:30.357

@KevinCruijssen Yeah, it seems like it works. I use zsh as my daily shell and it doesn't work in zsh without a space, I just assumed it wouldn't work in Bash but apparently it does. – betseg – 2017-03-24T09:25:40.910

7

R,11 bytes

sum(scan())

scan takes the input, one number per line. And sum, well, sums.

Frédéric

Posted 2017-03-23T20:36:11.547

Reputation: 2 059

7

Perl 5, 9 bytes

8 bytes of code + -p flag.

$\+=$_}{

Try it online!

With -p, the input is read one line at a time, stored in $_ each time. We use $\ as accumulator, because thanks to -p flag, it's implicitly printed at the end. The unmatched }{ are used so -p flag only prints $\ once at the end instead of printing $_ and $\ at each line it reads like it normally does.

Dada

Posted 2017-03-23T20:36:11.547

Reputation: 8 279

I can't even parse it! :) Explanation please. – None – 2017-03-24T08:23:30.597

@Lembik Here you go. – Dada – 2017-03-24T08:28:02.207

The unmatched parenthesise part is very obscure! – None – 2017-03-24T08:31:32.250

@Lembik Those aren't parenthesizes... They're either French or Curly Braces depends on who you ask, but they definitely are not )( – CraigR8806 – 2017-03-24T14:25:19.333

I have never heard them called French. I wonder what the French call them? – None – 2017-03-24T14:30:33.280

1@Lembik accolades, apparently. – Michael Vehrs – 2017-03-27T09:40:14.437

6

Haskell, 32 bytes

interact$show.sum.map read.lines

Try it online!.

interact collects the whole input from stdin, passes it to the function given as its argument and prints the string it gets back from this function. The function is:

            lines   -- split input into list of lines at nl
      map read      -- convert every line to a number (read is polymorphic,
                    -- but as want to sum it later, the type checker knows
                    -- it has to be numbers)
    sum             -- sum the list of numbers
show                -- convert back to string

nimi

Posted 2017-03-23T20:36:11.547

Reputation: 34 639

1This makes me really like Haskell. In Scala, I have to do lines.map(_.toInt)

because sum expects some sort of numeric implicit conversion from String or in this case an explicit one. – Stefan Aleksić – 2017-03-24T14:52:22.160

6

PHP, 22 bytes

<?=array_sum(file(t));

This assumes there is a file named "t" with a list of integers.

file() opens a file and returns an array with each line stored a separate element in the array. array_sum() sums all the elements in an array.

Kodos Johnson

Posted 2017-03-23T20:36:11.547

Reputation: 776

5

Awk, 19 bytes

{s+=$1}END{print s}

Explanation:

{s+=$1}                For all lines in the input, add to s
        END             End loop
           {print s}    Print s

Okx

Posted 2017-03-23T20:36:11.547

Reputation: 15 025

1"Explanation coming soon™" That'd be my new catchphrase if it weren't trademarked... – ETHproductions – 2017-03-23T20:55:55.130

2

In the language of awk, your answer is actually only 19 bytes: {s+=$1}END{print s} :)

– Digital Trauma – 2017-03-25T01:39:42.420

5

dc, 14 bytes

0[+?z2=a]dsaxp

Try it online!

Explanation:

 [      ] sa   # recursive macro stored in register a, does the following:
  +            # - sum both numbers on stack
               #   (prints to stderr 1st time since there's only 1)
   ?           # - read next line, push to stack as number
    z          # - push size of stack
     2         # - push 2
      =a       # - if stack size = 2, ? yielded something, so recurse
               # - otherwise end macro (implicit)
0              # push 0 (accumulator)
         d     # duplicate macro before storing it
            x  # Call macro
             p # The sum should be on the stack now, so print it

Brian McCutchon

Posted 2017-03-23T20:36:11.547

Reputation: 503

4

Python, 38 30 bytes

lambda n:sum(map(int,open(n)))

In python, files are opened by open('filename') (obviously). They are, however, iterables. Each time you iterate through the file, you get the next line. So map iterates over each list, calling int on it, and then sums the resulting list.

Call with the filename as input. (i.e. f('numbers.txt'))

8 bytes saved by using map(int, open(n)) instead of a list comprehension. Original code:

lambda n:sum([int(i)for i in open(n)]) 

Rɪᴋᴇʀ

Posted 2017-03-23T20:36:11.547

Reputation: 7 410

1I believe that you can also do this with standard input by calling 'open(0)'. Not sure if that can be used to shorten your answer. – cole – 2017-03-24T00:01:17.203

@Cole dennis already has that solution, so I'll leave my answer like this. – Rɪᴋᴇʀ – 2017-03-24T00:06:31.267

My mistake, sorry about that; I didn't read all the way through before coming to your answer. – cole – 2017-03-24T01:31:46.510

@Cole it's okay, I don't mind. – Rɪᴋᴇʀ – 2017-03-24T02:29:38.800

4

CJam, 5 bytes

q~]1b

Try it online!

How it works

q     e# Read all input from STDIN.
 ~    e# Evaluate that input, pushing several integers.
  ]   e# Wrap the entire stack in an array.
   1b e# Convert from base 1 to integer.
      e# :+ (reduce by sum) would work as well, but 1b handles empty arrays.

Dennis

Posted 2017-03-23T20:36:11.547

Reputation: 196 637

How does 1b sum numbers? – Esolanging Fruit – 2017-06-17T06:33:14.197

CJam doesn't require a canonical representation for digits-to-integer conversion; [<x> <y> <z> <w>]<b>b simply computes b³x + b²y + bz + w. When b = 1, this gives x + y + z + w. – Dennis – 2017-06-17T06:41:07.610

4

Mathematica, 19 bytes

Assumes Mathematica's notebook environment.

Tr[#&@@@Import@"a"]

Expects the input to be in a file a.

Martin Ender

Posted 2017-03-23T20:36:11.547

Reputation: 184 808

It's a crazy language :) – None – 2017-03-23T22:20:59.087

4@Lembik normal people would write this very readably as Total @ Flatten @ Import @ "a" or even "a" // Import // Flatten // Total. ;) – Martin Ender – 2017-03-23T22:32:24.637

Wouldn't Tr[#&@@@Import@#]& also be allowed? – ngenisis – 2017-03-24T18:27:39.300

4

Jelly, 9 8 bytes

ƈFпFỴVS

STDIN isn't really Jelly's thing...

Try it online!

How it works

ƈFпFỴVS  Main link. No arguments. Implicit argument: 0

  п      While loop; while the condition returns a truthy value, execute the body
          and set the return value to the result. Collect all results (including 0,
          the initial return value) in an array and return that array.
ƈ           Body: Yield a character from STDIN or [] if the input is exhausted.
 F          Condition: Flatten, mapping 0 to [], '0' to "0", and [] to [] (falsy).
    F     Flatten the result.
     Ỵ    Split at newlines.
      V   Evaluate the resulting strings.
       S  Take the sum.

Dennis

Posted 2017-03-23T20:36:11.547

Reputation: 196 637

1The second F could be a as well, for clarity. – Erik the Outgolfer – 2017-03-24T10:09:19.990

4

Brachylog, 4 bytes

ṇịᵐ+

Try it online!

Explanation

ṇ         Split the Input on linebreaks
 ịᵐ       Map: String to Integer
   +      Sum

Fatalize

Posted 2017-03-23T20:36:11.547

Reputation: 32 976

4

Pure bash, 30

read -d_ b
echo $[${b//'
'/+}]

Try it online.

  • reads the input file in one go into the variable b. -d_ tells read that the line delimiter is _ instead of newline
  • ${b//'newline'/+} replaces the newlines in b with +
  • echo $[ ... ] arithmetically evaluates the resulting expression and outputs it.

Digital Trauma

Posted 2017-03-23T20:36:11.547

Reputation: 64 644

+1 Very nice. Is the trailing newline of a input file read as well? I ask because if it is replaced by '+', the $[] section will error due to a trailing '+'. – seshoumara – 2017-03-25T07:48:13.727

@seshoumara It appears that read discards final trailing newlines, even though the line delimiter is overridden to _. This is perhaps a caveat of read, but it works well for this situation. – Digital Trauma – 2017-03-25T21:35:45.197

I am always happy to see a pure bash solution. – None – 2017-03-26T20:03:02.973

3

Vim, 16 bytes/keystrokes

:%s/\n/+
C<C-r>=<C-r>"<C-h>

Since V is backwards compatible, you can Try it online!

James

Posted 2017-03-23T20:36:11.547

Reputation: 54 537

Is this either reading from standard in or from a file? – None – 2017-03-23T22:39:25.660

Yeah, Vim might not be allowed...:( – CalculatorFeline – 2017-04-09T21:03:42.343

3

Pyth, 3 bytes

s.Q

Try it online!

 .Q  Read all of standard input, evaluating each line.
s    Take the sum.

Dennis

Posted 2017-03-23T20:36:11.547

Reputation: 196 637

3

jq, 5 bytes

add, plus the command line flag -s.

For example:

% echo "1\n2\n3\n4\n5" | jq -s add
15

Lynn

Posted 2017-03-23T20:36:11.547

Reputation: 55 648

6 bytes. Since -sadd won't work, count the space. – agc – 2017-03-25T16:37:17.580

@agc Correct me if I'm wrong but the code itself is add (3 bytes) and you have to add 2 bytes for the -s flag. The space doesn't count as the code or the flag: it's the command line separator used by the language. – caird coinheringaahing – 2017-03-28T21:01:50.463

1@ThisGuy, Well the -s flag is short for "--slurp", (read the entire input stream into a large array and run the filter just once), which changes both how jq interprets the input data, and how it runs the code. It's not like the -ein sed which merely tells sed that the subsequent string is code. The -s is more like a part of the jq language itself, and therefore that 6th byte space would be too. – agc – 2017-03-29T04:01:06.717

3

Actually, 2 bytes

Try it online!

Explanation:

kΣ
    (implicit input - read each line, evaluate it, and push it to the stack)
k   pop all stack elements and push them as a list
 Σ  sum
    (implicit output)

Mego

Posted 2017-03-23T20:36:11.547

Reputation: 32 998

3

dc, 22

[pq]sq0[?z2>q+lmx]dsmx

This seems rather longer than it should be, but it is tricky to decide when the end of the file is reached. The only way I can think of to do this is check the stack length after the ? command.

Try it online.

[pq]                    # macro to `p`rint top-of-stack, then `q`uit the program
    sq                  # save the above macro in the `q` register
      0                 # push `0` to the stack.  Each input number is added to this (stack accumulator)
       [         ]      # macro to:
        ?               # - read line of input
         z              # - push stack length to stack
          2             # - push 2 to the stack
           >q           # - if 2 > stack length then invoke macro stored in `q` register
             +          # - add input to stack accumulator
              lmx       # - load macro stored in `m` register and execute it
                  d     # duplicate macro
                   sm   # store in register `m`
                     x  # execute macro

Note the macro m is called recursively. Modern dc implements tail recursion for this sort of thing, so there should be no worries about overflowing the stack.

Digital Trauma

Posted 2017-03-23T20:36:11.547

Reputation: 64 644

Welcome to PPCG! Please note that if there isn't enough explanations it will go through the low quality posts filter. – Matthew Roh – 2017-03-25T02:40:47.573

@SIGSEGV no welcome necessary - I've been here a while ;-). Yep, I was writing my explanation while you commented. See edit. – Digital Trauma – 2017-03-25T03:22:37.887

1I owe you a byte for the trick of duplicating the macro before storing it. – Brian McCutchon – 2017-03-27T20:01:15.497

2

Python 2, 50 45 43 bytes

Pretty self-explanatory.

s=0
try:
    while 1:s+=input()
except:print s

Try it online

mbomb007

Posted 2017-03-23T20:36:11.547

Reputation: 21 944

2I think any error suffices for break, since programs can terminate in error by default. An unitialized variable would do. – xnor – 2017-03-23T20:51:27.547

4Better yet, the while can be in the try block. – xnor – 2017-03-23T20:54:43.960

Use only 1 space before while 1:. If you're using tabs SE messes them up. – CalculatorFeline – 2017-04-09T21:03:10.633

@CalculatorFeline If you "edit" the post you can see it's a real tab. You can also see it's a real tab on TIO. I prefer tabs to spaces. – mbomb007 – 2017-04-10T03:04:47.187

Good to know.`` – CalculatorFeline – 2017-04-10T21:27:04.070

2

Pyke, 4 bytes

zbrs

Try it online!

z    -   input()
 b   -  int(^)
  r  - if no errors: goto start
   s - sum(stack)

Blue

Posted 2017-03-23T20:36:11.547

Reputation: 26 661

2

GS2, 2 bytes

Wd

Try it online!

How it works

    (implicit) Read all input from STDIN an push it as a string.
W   Extract all integers, pushing a single array.
    For input x, this executes map(int, re.findall(r'-?\d+', x)) internally.
 d  Take the sum.

Dennis

Posted 2017-03-23T20:36:11.547

Reputation: 196 637

2

GNU sed + bc, 34 bytes

:
$!N
$!b
y:\n:+:
s:.*:echo &|bc:e

Try it online!

It is possible to do a shell call from inside sed, and as such I use bc to calculate the sum. Lines 1 to 4 only prepare the input necessary for that calculation. This works for negative numbers as well.

Explanation:

:                    # start reading loop
$!N                  # if not EOF, read and append a new input line to pattern
$!b                  # repeat
y:\n:+:              # turn all newlines into pluses
s:.*:echo &|bc:e     # shell call to bc with pattern as input (calculates sum)
                     # implicit printing

Pure GNU sed program: 236 + 1(r flag) = 237 bytes (as promised some time ago)

There are no data types or any math operations in sed. I have tried various methods, but it turns out that concatenating the numbers in unary format and converting the result back to decimal is the simplest way. This works for non-negative integers only, compared to the code above, however this is precisely what the challenge stated in the first place.

G;s:\n::
# concatenate current decimal number with the intermediary unary sum, if any
h;:;s:\w::2g;y:9876543210:87654321\t :;/ /!s:;|$:@:;/\s/!t;x;s:.::;x;G;s:;.*::m;s:\s::g;/\w/{s:@:&&&&&&&&&&:g;t}
# convert the decimal number to unary (using '@' as digit)
y:@:;:
# change unary digit from '@' to ';', to not interfere with above on the next cycle
h;$!d
# store intermediary unary sum and start next reading cycle if input lines left
s:^:0:;/;/{:d;s:^9+:0&:;s:.9*;:/&:;h;s:.*/::;y:0123456789:1234567890:;x;s:/.*::;G;s:\n::;s:;::;/;/td}
# convert final unary sum to decimal (result), plus implicit printing at the end

Try it online!

The program does bignum arithmetic, as long as sed can store in memory the unary result.

seshoumara

Posted 2017-03-23T20:36:11.547

Reputation: 2 878

2

Powershell, 18 Bytes

(gc 1)-join"+"|iex

this assumes the file is named '1' with no extension.

alternate 24 byte version, takes filename as input:

(gc "$args")-join"+"|iex

explanation:

( get content of the file "$args" ) then -join the lines together with a "+" to form a valid-syntax sum, then | invoke expression to calculate it as if it was typed into the console directly.

if output is allowed in the following format:

Count    : 3
Average  :
Sum      : 227
Maximum  :
Minimum  :
Property :

then gc 1|measure -s is a valid 15 byte solution, thanks to @AdmBorkBork for pointing that out.

colsw

Posted 2017-03-23T20:36:11.547

Reputation: 3 195

Your 18 byte version is valid. – None – 2017-03-24T06:05:52.013

@Lembik Thanks, wasn't 100% sure if the no-extension would be allowed, updated the answer there. – colsw – 2017-03-24T09:59:15.347

If extraneous output is allowed, you can do gc 1|measure -s for 15 – AdmBorkBork – 2017-03-24T13:23:02.427

@Lembik see AdmBorkBork's suggestion, if all the 'extra' text is allowed let me know and I can update my answer, thanks! – colsw – 2017-03-24T17:07:37.240

I don't think that is allowed but it is nice. – None – 2017-03-24T17:08:41.787

1@Lembik thanks for clearing that up - i'll leave it as a note anyway as it is interesting. – colsw – 2017-03-24T17:09:07.843

2

Batch, 55 bytes

@set s=0
@for /f %%n in (%1)do @set/as+=%%n
@echo %s%

Takes the file to be summed as a command-line parameter.

Neil

Posted 2017-03-23T20:36:11.547

Reputation: 95 035

Do you have to do set s=0 in the beginning? It will work on the first run without it, won't it? – Kodos Johnson – 2017-03-24T16:14:43.140

1@KodosJohnson I'm not sure that's legal in code golf; as I recall the same applies to being able to call a function more than once without the caller resetting global variables to zero in between. – Neil – 2017-03-24T17:14:40.130

2

Ruby, 19 15 bytes

Loving that new #sum in Ruby 2.4 :)

p$<.sum(&:to_i)

This program accepts input from either stdin or any filename(s) given as command line argument

daniero

Posted 2017-03-23T20:36:11.547

Reputation: 17 193

For those of us without 2.4 (including TIO…) p$<.map(&:to_i).inject(:+) – snail_ – 2017-03-26T08:12:49.457

2

MATLAB: 17 bytes

sum(dlmread('x'))

Assumes a file named 'x' in current directory. dlmread reads numeric values from a file using delimiters - if no delimiter is specified as the second argument, it will infer from the file type. It successfully infers \n as the delimiter in a file as specified by the question, then uses sum to add them up.

Hugh Nolan

Posted 2017-03-23T20:36:11.547

Reputation: 191

2

QBasic 4.5, 61 59 bytes

Since QBasic isn't the greatest with streams, the input is assumed in a file called "a".

Minus 2 bytes because @DLosc showed me an alternate syntax for one of QBasic's most iconic commands. Does QBasic really hold no secrets for you?

OPEN"I",1,"a"
WHILE EOF(1)=0:INPUT#1,b$:x=x+VAL(b$)
WEND:?x

steenbergh

Posted 2017-03-23T20:36:11.547

Reputation: 7 772

2

C#, 121 bytes

Java, but no C#? That will not do...

using C=System.Console;class P{static void Main(){int a=0,b;for(;int.TryParse(C.ReadLine(),out b);)a+=b;C.WriteLine(a);}}

Try it Online

Since this score is worse than Java's, we'd better provide a 95 byte context-less function also:

using C=System.Console;int S(){int a=0,b;for(;int.TryParse(C.ReadLine(),out b);)a+=b;return a;}

Formatted and commented:

using C=System.Console;

class P
{
    static void Main()
    {
        int a=0,b; // a is accumulator, b is tempory storage
        for(;int.TryParse(C.ReadLine(),out b);) // read a line, try to parse it as an integer (expects a trailing new-line)
            a+=b; // add to accumulator
        C.WriteLine(a); // print accumulator
    }
}

I was really hoping to have some code like the following:

int a=0,b=0,c;
for(;(c=C.Read())>0;)
    b=c<15?(a+=b)*0:b*10+c-48;
C.WriteLine(a);

But it just doesn't pay :(

Just for fun, the try...catch solution is also 121 bytes

using C=System.Console;class P{static void Main(){int a=0;try{for(;;)a+=int.Parse(C.ReadLine());}catch{}C.WriteLine(a);}}

VisualMelon

Posted 2017-03-23T20:36:11.547

Reputation: 3 810

2

Pip, 4 bytes

3 bytes of code, +1 for -r flag.

$+g

Try it online!

$+g is the standard "sum all inputs" program--read it as fold-plus(arglist). Normally the arglist is taken from command-line arguments. The -r flag takes it from lines of stdin instead.

DLosc

Posted 2017-03-23T20:36:11.547

Reputation: 21 213

2

PostScript, 11

Consists of two files. File A: (2 bytes)

0[

File B: (8 bytes tokenized)

]{add}forall =

Invoke as: (1 byte for extra file)

$ gs a inputfile b

This takes advantage of the fact that the input format is also valid PostScript code that just pushes all the numbers on the stack.

This allows it to very cheaply create an array from them over which it can iterate, by using multiple files to place an initial value for the summation and the opening brace on the stack before the input file.

AJMansfield

Posted 2017-03-23T20:36:11.547

Reputation: 2 758

Thank you. Can you do it in pdf too? – None – 2017-03-25T11:42:56.420

@Lembik I'll see, it's a bit harder to do actual computation in PDF since it only contains a subset of the operators and a bunch of security limitations. – AJMansfield – 2017-03-27T14:56:32.447

2

Go, 146 bytes

package main
import("bufio";"os";"strconv")
func main(){
s:=bufio.NewScanner(os.Stdin)
n:=0
for s.Scan(){m,_:=strconv.Atoi(s.Text())
n+=m
print(n)}}

Eric Lagergren

Posted 2017-03-23T20:36:11.547

Reputation: 473

2

Cubix, 15 bytes

I have two versions to do this. The first (and longest) is to specification. This will work with non negative integers only. A negative integer will be treated as a end of input, but zeros will be handled correctly.

O<u;Ii?;+...@._

Try it here
Expanded onto the cube

    O <
    u ;
I i ? ; + . . .
@ . _ . . . . .
    . .
    . .

This essentially reads in an integer and the seperator. If the separator is negative (EOF or negative) redirect up into a path that will remove two items from the stack, output the already summed results, grab a superfluous input and exit. Otherwise if the input is non negative remove from the stack then sum. This creates a rolling total.

The shorter (8 byte) non-compliant version will handle non-zero integers, but it treats 0 on the stack as the end of input.

@O;UI!W+

Try it here

    @ O
    ; U
I ! W + . . . .
. . . . . . . .
    . .
    . .

MickyT

Posted 2017-03-23T20:36:11.547

Reputation: 11 735

2

Tcl, 33 bytes

puts [expr [join [read stdin] +]]

Try it online!

sergiol

Posted 2017-03-23T20:36:11.547

Reputation: 3 055

Got some bytes less thanks to @Johannes Kuhn – sergiol – 2017-09-16T13:50:06.983

2

Java 7, 109 Bytes

import java.util.*;int x;int s(){Scanner a=new 
Scanner(System.in);while(a.hasNext())x+=a.nextInt();return x;}

Try it!

Reads from System.in

Twometer

Posted 2017-03-23T20:36:11.547

Reputation: 281

2

QBIC, 19 bytes

{_?~A=Z|_Xp\p=p+!A!

Explanation

{        DO infinitely
_?       Ask for user input, save as A$
~A=Z     IF input was nothing (Z$ = "")
|_Xp     THEN QUIT, printing the total
\p=p+    ELSE increase the total by
     A   the given input
    ! !  cast as a number

steenbergh

Posted 2017-03-23T20:36:11.547

Reputation: 7 772

2

T-SQL, 60 59 bytes

SELECT 0a INTO n;BULK INSERT n FROM'd:n'SELECT SUM(a)FROM n

This is the kind of thing that SQL was designed to do, surprised there isn't already an answer for it. Tested on MS SQL 2012.

SELECT 0a INTO n; is slightly shorter than CREATE TABLE n(a INT). Adding a zero row doesn't change the total.

Text file named n (no extension) is located in the current folder on the D: drive. BULK INSERT is shorter and easier than other file import options like SELECT FROM OPENROWSET(BULK) or EXEC xp_cmdshell 'bcp.exe'.

Of course if input is allowed via a pre-existing table, per our normal I/O standards, then this would be trivial (19 bytes):

SELECT SUM(a)FROM n

But of course this challenge is all about the IO...

BradC

Posted 2017-03-23T20:36:11.547

Reputation: 6 099

2

Implicit, 4 3 bytes

©1Þ

I'm going to add a builtin for ©1 eventually (e.g. when I'm done working on bitwise). (Just kidding, I'm never going to get around to it.)

Explanation:

©1Þ
©1   consume all input as integers
  Þ  sum the entire stack

Try it online!

MD XF

Posted 2017-03-23T20:36:11.547

Reputation: 11 605

1

Labyrinth, 8 bytes

?+
;,;!@

Try it online!

The left-most 2x2 block is the main loop:

?   Read integer.
+   Add to running total (initially zero).
,   Read character. 10 as long as there is another input, -1 at EOF which will
    exit the loop.
;   Discard the 10.

Once we hit EOF, the IP moves east from the ,.

;   Discard the -1.
!   Output the sum.
@   Terminate the program.

Martin Ender

Posted 2017-03-23T20:36:11.547

Reputation: 184 808

1

Java 7, 111 bytes

import java.util.*;int c(){Scanner c=new Scanner(System.in);int r=0;for(;c.hasNext();r+=c.nextInt());return r;}

Takes the input from STDIN.

Try it here.

Kevin Cruijssen

Posted 2017-03-23T20:36:11.547

Reputation: 67 575

Java, the black sheep of the golfing family :) – None – 2017-03-24T08:55:17.703

1

@Lembik Yep.. I can usually compete with BrainFuck, C# and other longer languages, but Java certainly will never win a golfing contest. The only accepted Java answer I've seen so far was for a [popularity-contest]. But it's still fun to golf in Java imo, and once in a while something is pretty short compared to other submissions - in Java 8 that is :)

– Kevin Cruijssen – 2017-03-24T10:38:53.770

1

JavaScript (Node.js), 124 bytes

t=0;
r=require('readline').createInterface({input:process.stdin});
r.on('line',l=>{t-=-l});
r.on('close',()=>console.log(t))

Try it online!

alebianco

Posted 2017-03-23T20:36:11.547

Reputation: 171

119 bytes: t=0;with(require('readline').createInterface({input:process.stdin}))on('line',l=>{t-=-l}),on('close',_=>console.log(t)) – Ismael Miguel – 2017-03-26T17:33:09.197

@IsmaelMiguel You can do even better with chaining, so: my answer.

– Brian McCutchon – 2017-03-26T20:27:52.760

1

Julia, 44 bytes

print(sum(map(s->parse(Int,s),readlines())))

David Conrad

Posted 2017-03-23T20:36:11.547

Reputation: 1 037

A Julia answer is very warmly welcomed! – None – 2017-03-24T13:48:44.080

1

Jellyfish, 24 bytes

p
/
+
j, ,']
1'[J-1
   0

Try it online!

Explanation

Reading input isn't very flexible in Jellyfish. In particular, there's no easy way to read a variable number of integers from STDIN, except as a list literal. So the majority of this code is input.

The shortest way I've found is to read all of STDIN as a string, then wrap it in [...] and then evaluate the string. Thankfully, Jelly's parser only looks for whitespace as a separator in lists, not specifically for space characters. So the linefeed separation required by the challenge works.

So let's build up the code from the bottom:

   J-1
   0

Read all input.

   ,']
   J-1
   0

Append ].

 , ,']
 '[J-1
   0

Prepend [.

j, ,']
1'[J-1
   0

Evaluate.

/
+
j, ,']
1'[J-1
   0

Fold addition (in other words, sum).

p
/
+
j, ,']
1'[J-1
   0

Print the result.

Martin Ender

Posted 2017-03-23T20:36:11.547

Reputation: 184 808

1

C++, 99 Bytes

using namespace std;int main(){string a;int b=0;while(1){getline(cin,a);cout<<(b+=stoi(a))<<"\n";}}

Not my finest work, and there's probably a far better way to go about doing this. Still, I figured that using a string was the optimal way of doing things, seeing as I felt conversions with 'cin' would take up a vast majority of my code otherwise.

Enjoy!

Monkah VII

Posted 2017-03-23T20:36:11.547

Reputation: 191

You could save a few bytes by just wrapping the function in namespace std{ and declaring the function as ::main, rather than using using. – AJMansfield – 2017-03-25T06:57:28.910

1

Scala, 48 bytes

print(io.Source.stdin.getLines.map(_.toInt).sum)

Brian McCutchon

Posted 2017-03-23T20:36:11.547

Reputation: 503

1

JavaScript (Node.js), 112 bytes

Improvements upon the other JavaScript answer and comment below it.

a=0
require('readline').createInterface({input:process.stdin}).on('line',l=>a+=+l).on('close',_=>console.log(a))

Try it online!

Given the split module (npm install split), it's much shorter:

JavaScript (Node.js) with split module, 90 bytes

a=0
process.stdin.pipe(require('split')()).on('data',l=>a+=+l).on('end',_=>console.log(a))

Brian McCutchon

Posted 2017-03-23T20:36:11.547

Reputation: 503

1

REXX, 47 bytes

s=0
pull n
do until n=''
  s=s+n
  pull n
  end
say s

idrougge

Posted 2017-03-23T20:36:11.547

Reputation: 641

1

Alice, 11 bytes

/o
\i@/Hd&+

Try it online!

This feels a bit suboptimal with all those mirrors (and also because the H could also be a +, possibly allowing reuse there), but so far I've only found a handful of different 11-byte solutions.

Explanation

/o
\i@/...

While it's sometimes possible to shorten it, this seems to be a good pattern for programs which a) one or more integers as input, b) transform them with a linear program in Cardinal mode (i.e. integer processing mode), c) want to output one integer. The instruction pointer (IP) first moves from / to / bouncing through the i which reads all input. Then the ... is executed and the IP wrap around to the wrong. The \ puts the IP again in Ordinal mode where o prints the integer as a decimal string and @ terminates the program. So that's the framework I'm using here.

The core of the program is then just four commands:

H   Compute the absolute value of the top of the stack. The reason we're doing this
    is that the stack still holds the entire input as a string. But as soon as you
    try to pop a value in Cardinal mode, that string gets implicitly converted
    to the integers it contains. So in this case, the H itself doesn't really
    do anything but it forces the input to be converted. We could also use
    + here and already sum the top two values (if there's only one value it
    would get added to an implicit zero, so that's fine).
d   Push the stack depth, i.e. the number of integers in the input.
&   Execute the next command that many times.
+   Add the top two numbers of the stack. Of course this is one more addition
    than we need, but there are only implicit zeros beneath the input so
    they don't change the result.

Martin Ender

Posted 2017-03-23T20:36:11.547

Reputation: 184 808

1

Triangular, 15 bytes

(\$]U]P.%p/+U(<

Try it online!

Formats into this triangle:

    (
   \ $
  ] U ]
 P . % p
/ + U ( <

Explanation:

The IP starts from the top of the triangle, moving Southeast. So the first code that is executed is this:

($]

That simply reads integers as input until there is no more input.

This is how the interpreter sees the next part:

p(U+P]U%
  • p pops the EOF from the stack.
  • ( opens a loop (to add the inputted integers).
  • U pulls the "memory" (register) value onto the stack if it is not zero.
  • + adds the top two stack values together, pops them, and pushes the result.
  • P pops the top of stack into memory. Now, if we've added all inputted integers together, nothing will be on the stack.
  • ] ends the loop if the top of the stack is falsy (or the stack is empty).
  • U pulls the memory value onto the stack.
  • % prints it.
  • Another loop is created at the end of the code, but that doesn't do anything as the IP runs off the playing field and terminates.

MD XF

Posted 2017-03-23T20:36:11.547

Reputation: 11 605

1

JavaScript (Node.js), 78 bytes

process.stdin.on("data",r=>console.log((""+r).split`
`.reduce((a,v)=>+a+ +v)))

No requires needed for this one, just native NodeJS.

Try it online!

Justin Mariner

Posted 2017-03-23T20:36:11.547

Reputation: 4 746

1

Dart, 96 bytes (non async), 132 bytes (async)

Non async:

import'dart:io';main(){_ s;_ i=0;while((s=stdin.readLineSync())!=null)i+=int.parse(s);print(i);}

Dart allows you to define local variables with types that don't exist when running in uncheck mode (which is the default mode). This program doesn't function in checked mode.

Async:

import'dart:io';import'dart:convert';main()async=>print((await UTF8.decodeStream(stdin)).split("\n").fold(0,(p,e)=>p+int.parse(e)));

The async version is longer, easier to read, and faster than the sync version. It also works in checked mode. UTF8.decodeStream decodes the entire stream into a Future, await waits for this to finish and gives a String, the string is split by line into List, and finally the strings are folded into the final result.

Dwayne Slater

Posted 2017-03-23T20:36:11.547

Reputation: 111

1

Lua, 59 bytes 57 bytes

New code: 57 bytes

i,s=0,0;repeat i,s=i+s,io.read("*l")until not s print(i)

We initialize i and s to 0. For each iteration, we add s to i and load in a new s from stdin. Lua has implicit string -> number coercions when doing numeric operations on a string.


Old code: 59 bytes

i=0;io.read("*a"):gsub(".-\n",function(g)i=i+g end)print(i)

Takes entire stdin and turns it into a string, gsubs over the entire string to extract lines, uses implicit number conversion and adds the lines to i, then prints i.

Dwayne Slater

Posted 2017-03-23T20:36:11.547

Reputation: 111

1

Carrot, 6 bytes

#^A
+ 

Note the trailing space after the +.

Explanation:

#   //Set the stack to the entire input
^   //Convert to operations mode
A\n //Split the stack into an array on a new line
+   //Add all the arguments of the array together
    //Implicitly output the result

TheLethalCoder

Posted 2017-03-23T20:36:11.547

Reputation: 6 930

This is one of the reasons I am doing the rewrite of Carrot. With the new lexer, the space after + would not be needed as it will be understood that + takes no arguments. – user41805 – 2017-07-19T13:16:06.280

@Cowsquack Ah nice that'll be good. – TheLethalCoder – 2017-07-19T13:17:58.693

1

Ly, 2 bytes

&+

Try it online!

A Ly builtin that would beat the accepted answer if it wasn't a 2-byte builtin...

LyricLy

Posted 2017-03-23T20:36:11.547

Reputation: 3 313

1

q/kdb+, 14 bytes

Solution:

sum"J"$(0:)`:f

Example:

q)system "cat f" / check contents of file f
"123"
,"5"
"99"
q)sum"J"$(0:)`:f
227

Explanation:

Read in the file called f, cast to longs, sum up:

sum"J"$read0`:f / ungolfed solution
            `:f / our input file f
       read0    / read in a file, break on newlines
   "J"$         / parse strings to longs
sum             / sum it up

Bonus:

The solution in K4 is 10 bytes. Eequivalent to sum value each read0 `:f in Q:

+/.:'0:`:f

streetster

Posted 2017-03-23T20:36:11.547

Reputation: 3 635

1

Wumpus, 11 8 bytes

I+0i.
O@

Try it online!

Explanation

As long as there are numbers left to read, the program loops through the first line:

I   Read a decimal integer from STDIN.
+   Add it to the top of the stack. Initially, the stack is empty, which adds
    the first number to an implicit zero.
0   Push 0.
i   Read the next byte. If there are numbers left, this will be a 10 (for the
    separating linefeed). Otherwise, we're at EOF and this gives -1.
.   Jump to (0, x), where x is the byte we just read, modulo 2 (because the
    program is 2 rows tall). So for a linefeed, this jumps to the beginning
    of the first line, and at EOF this jumps to the beginning of the second
    line.

Once we run out of numbers to add, control flow goes to the second line:

O   Print the sum as a decimal integer.
@   Terminate the program.

Martin Ender

Posted 2017-03-23T20:36:11.547

Reputation: 184 808

1

Flobnar, 16 12 bytes

-4 bytes thanks to @JoKing

+>p*
^@
>&06

Try it online! Requires the -d flag.

As a bonus, this works if no numbers are passed, and supports pretty much any separator other than digits and -.

Esolanging Fruit

Posted 2017-03-23T20:36:11.547

Reputation: 13 542

12 bytes – Jo King – 2018-08-17T11:05:20.890

@JoKing I have no idea how that works, but ok... – Esolanging Fruit – 2018-08-19T07:03:35.063

1

APL (Dyalog Unicode), 12 bytes

Complete program.

+/⍎⍕⊃⎕NGET⍞1

Try it online!

 read filename from stdin

⊃⎕NGET1 get native file content as list of strings

 stringify (puts two spaces between lines)

 execute (as APL code)

+/ sum

Adám

Posted 2017-03-23T20:36:11.547

Reputation: 37 779

0

Sinclair ZX81 (16K only - probably*) File size according to EightyOne - 163** bytes (yes 163!) Byte count undetermined

Firstly, we should make our file, so using direct mode, type:

LET A=123
LET B=5
LET C=99

To make sure that they are there, print them to the screen, as follows:

PRINT A,,B,,C

This should appear on the display:

ZX81 variable output

Now, to save this to file (as the variable stack is saved along with other important memory locations used by the interpreter), simply type:

SAVE "SUM"

If you're using a real ZX81 then press play and record on tape, whilst emulators like EightyOne will create a tape image for you.

Now clear the RAMs with:

RAND USR 0

or:

NEW

Now rewind the tape (or the emulator should auto-detect and start the virtual tape from the beginning), and type:

LOAD "SUM"

So our file is back in memories, so we need to add it together. Simply:

PRINT A+B+C

And the answer is:

The ZX81 final output

*I specify 16K because any less and the ZX81 will typically rearrange the memory and this could affect the var stack (mostly to do with collapsing the DFILE), as the DFILE is static with 16K then this should be less of an issue.

**The ZX81 file is saving more than just the VAR stack of three whole variables above, and although each number appears to be an integer, the ZX81 is storing these variables as 24-bit floating point numbers rather than 1 byte integers.

Shaun Bebbers

Posted 2017-03-23T20:36:11.547

Reputation: 1 814

Utterly brilliant . Let's not mention the spec :) – None – 2017-03-24T10:03:36.700

I'm confused what the actual code is. Is that PRINT A+B+C part of it? Would it be invalid then if there are more or less than 3 numbers? – Luis Mendo – 2017-03-24T11:45:48.217

The challenge seemed to specifically require a file, and to do that on a ZX81 you need to save your values somewhere. I decided to use the 24-bit floating point variables that I named A, B, and C. I could have POKEd these values to a spare bit of memory but I'm not sure if it'll save. So if you wanted more variables, then you'd need to initialise and declare more variables, so if LET D=321 and that was SAVEd then to add up the file contents, one would PRINT A+B+C+D. I could save to a string but I'd been some way to separate each individual number by a comma, for instance. – Shaun Bebbers – 2017-03-24T11:53:49.717

Remember, I initialised and declared the variable values, then saved that to a file before clearing the memory. I then loaded back the file using the ZX81's equivalent of standard in - once the file was loaded, the variables were back in memory, so therefore I could use the PRINT keyword to add up and output the values. – Shaun Bebbers – 2017-03-24T11:56:07.870

1@ShaunBebbers The same program needs to work for an arbitrary number of values without modification. – AJMansfield – 2017-03-25T07:01:17.053

So how to create files and read them on a ZX81 then... Okay back to 101. – Shaun Bebbers – 2017-03-25T07:38:42.140

Also note that the program must use the input format specified in the question. – AJMansfield – 2017-03-25T18:29:54.943

Sure but programming standards were very different in 1981 - standard in? INPUT A then. – Shaun Bebbers – 2017-03-25T18:59:13.643

This is why I suggested having one liners and golfing in the Retro Computing stack exchange. – Shaun Bebbers – 2017-03-25T19:00:50.763

0

Anyfix, 4 bytes

ɦ€#S

Explanation

ɦ€#S  Program
ɦ     Exhaust input; read into a list of lines
 €    Map: 
  #        Parse to number
   S  Sum

HyperNeutrino

Posted 2017-03-23T20:36:11.547

Reputation: 26 575

0

JavaScript (ES6), 27 bytes

s=>eval(s.split`
`.join`+`)

Try it

f=
s=>eval(s.split`
`.join`+`)
oninput=_=>o.innerText=f(i.value);o.innerText=f(i.value=`123\n5\n99`)
textarea{font-family:sans-serif;height:100px;width:100px;}
<textarea id=i></textarea><pre id=o>


Explanation

  • Takes input as a multiline string via parameter s.
  • Splits the string to an array on newlines.
  • Joins the array to a string on +.
  • Evals the string to give us the sum.

Alternative, 23 bytes

If we could take each integer as an individual argument of our function then we could do this:

(...a)=>eval(a.join`+`)

Alternative, 63 bytes

If we have to take a file name as input then use this version instead:

p=>fetch(p).then(r=>r.text()).then(s=>eval(s.split`
`.join`+`))

Shaggy

Posted 2017-03-23T20:36:11.547

Reputation: 24 623

0

Stax, 2 bytes

|+

Run and debug it

Also prints intermediate results, which doesn't appear to be disallowed

vazt

Posted 2017-03-23T20:36:11.547

Reputation: 311

0

C++, 98 bytes

#include<regex>
namespace std{int::main(){istream_iterator<int>a{cin},b;cout<<accumulate(a,b,0);}}

Ungolfed

#include <iterator>
#include <numeric>
#include <iostream>

int main()
{
    std::istream_iterator<int> first{std::cin};
    std::istream_iterator<int> last{};
    std::cout << std::accumulate(first, last, 0);
}

We have std::istream_iterator to read input as whitespace-separated integers, and std::accumulate to add them up.

Toby Speight

Posted 2017-03-23T20:36:11.547

Reputation: 5 058

0

Ahead, 13 bytes

~Ilj~#
 >K+O@

Try it online!

snail_

Posted 2017-03-23T20:36:11.547

Reputation: 1 982

0

Scheme, 48 bytes

(write(let l((x 0))(if(real? x)(+(l(read))x)0)))

Try it online! (Chicken Scheme, but this works on other schemes as well)

(write ... ) write to STDOUT the result of

  • (let l ... ) looping special form named l

    • ((x 0)) initially declare x as 0
    • (if ... ) if
      • (real? x) x is real, i.e. not EOF,
      • (+ ... ) add
        • (l(read)) the result of this loop called with x set as the value read from STDIN
        • x with x
      • 0 else give 0

user41805

Posted 2017-03-23T20:36:11.547

Reputation: 16 320