Sum of squares: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Kotlin}}: Add other approaches, and discuss pros and cons.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(45 intermediate revisions by 27 users not shown)
Line 12: Line 12:


=={{header|0815}}==
=={{header|0815}}==
<lang 0815>
<syntaxhighlight lang="0815">
{x{*%<:d:~$<:1:~>><:2:~>><:3:~>><:4:~>><:5:~>><:6:~>><:7:
{x{*%<:d:~$<:1:~>><:2:~>><:3:~>><:4:~>><:5:~>><:6:~>><:7:
~>><:8:~>><:9:~>><:a:~>><:b:~>><:c:~>><:ffffffffffffffff:
~>><:8:~>><:9:~>><:a:~>><:b:~>><:c:~>><:ffffffffffffffff:
~>{x{*>}:8f:{x{*&{=+>{~>&=x<:ffffffffffffffff:/#:8f:{{~%
~>{x{*>}:8f:{x{*&{=+>{~>&=x<:ffffffffffffffff:/#:8f:{{~%
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
0
0
28A
28A
</pre>

=={{header|11l}}==
<syntaxhighlight lang="11l">print(sum([1, 2, 3, 4, 5].map(x -> x^2)))</syntaxhighlight>

{{out}}
<pre>
55
</pre>
</pre>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Sum of squares 27/08/2015
<syntaxhighlight lang="360asm">* Sum of squares 27/08/2015
SUMOFSQR CSECT
SUMOFSQR CSECT
USING SUMOFSQR,R12
USING SUMOFSQR,R12
Line 47: Line 55:
N DC AL2((PG-A)/4)
N DC AL2((PG-A)/4)
YREGS
YREGS
END SUMOFSQR</lang>
END SUMOFSQR</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 55: Line 63:
=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==


<lang asm> ;;; Sum of squares
<syntaxhighlight lang="asm"> ;;; Sum of squares
cpu 8086
cpu 8086
bits 16
bits 16
Line 109: Line 117:
outstr_end: db '$'
outstr_end: db '$'
array: dw 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
array: dw 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
arrlen: equ ($-array)/2 ; length is in words</lang>
arrlen: equ ($-array)/2 ; length is in words</syntaxhighlight>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun sum-of-squares (xs)
<syntaxhighlight lang="lisp">(defun sum-of-squares (xs)
(if (endp xs)
(if (endp xs)
0
0
(+ (* (first xs) (first xs))
(+ (* (first xs) (first xs))
(sum-of-squares (rest xs)))))</lang>
(sum-of-squares (rest xs)))))</syntaxhighlight>

=={{header|Action!}}==
<syntaxhighlight lang="action!">CARD FUNC SumOfSqr(BYTE ARRAY a BYTE count)
BYTE i
CARD res

IF count=0 THEN
RETURN (0)
FI

res=0
FOR i=0 TO count-1
DO
res==+a(i)*a(i)
OD
RETURN (res)

PROC Test(BYTE ARRAY a BYTE count)
BYTE i
CARD res

res=SumOfSqr(a,count)
Print("[")
IF count>0 THEN
FOR i=0 to count-1
DO
PrintB(a(i))
IF i<count-1 THEN
Put(' )
FI
OD
FI
PrintF("]->%U%E%E",res)
RETURN

PROC Main()
BYTE ARRAY a=[1 2 3 4 5]
BYTE ARRAY b=[10 20 30 40 50 60 70 80 90]
BYTE ARRAY c=[11]
Test(a,5)
Test(b,9)
Test(c,1)
Test(c,0)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_of_squares.png Screenshot from Atari 8-bit computer]
<pre>
[1 2 3 4 5]->55

[10 20 30 40 50 60 70 80 90]->28500

[11]->121

[]->0
</pre>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>function sumOfSquares(vector:Vector.<Number>):Number
<syntaxhighlight lang="actionscript">function sumOfSquares(vector:Vector.<Number>):Number
{
{
var sum:Number = 0;
var sum:Number = 0;
Line 125: Line 189:
sum += vector[i]*vector[i];
sum += vector[i]*vector[i];
return sum;
return sum;
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure Test_Sum_Of_Squares is
procedure Test_Sum_Of_Squares is
Line 145: Line 209:
Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array
Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array
Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0))));
Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0))));
end Test_Sum_Of_Squares;</lang>
end Test_Sum_Of_Squares;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 153: Line 217:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>real
<syntaxhighlight lang="aime">real
squaredsum(list l)
squaredsum(list l)
{
{
Line 180: Line 244:


0;
0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>14
<pre>14
0
0
4.5</pre>
4.5</pre>

=={{header|ALGOL 60}}==
{{works with|GNU Marst|Any - tested with release 2.7}}
Using [[Jensen's Device]].
<syntaxhighlight lang="algol60">
begin
integer i;
integer array A[ 1 : 5 ];
real procedure sum (i, lo, hi, term);
value lo, hi;
integer i, lo, hi;
real term;
comment term is passed by-name, and so is i;
begin
real temp;
temp := 0;
for i := lo step 1 until hi do
temp := temp + term;
sum := temp
end;
comment initialie A;
for i := 1 step 1 until 5 do A[i] := i;
comment note the correspondence between the mathematical notation and the call to sum;
outreal(1, sum (i, 1, 5, A[i] * A[i]))
end
</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 194: Line 284:


The computation can be written as a loop.
The computation can be written as a loop.
<lang algol68>PROC sum of squares = ([]REAL argv)REAL:(
<syntaxhighlight lang="algol68">PROC sum of squares = ([]REAL argv)REAL:(
REAL sum := 0;
REAL sum := 0;
FOR i FROM LWB argv TO UPB argv DO
FOR i FROM LWB argv TO UPB argv DO
Line 203: Line 293:
test:(
test:(
printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));
printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 211: Line 301:


{{trans|python}}
{{trans|python}}
<lang algol68>[]REAL data = (3, 1, 4, 1, 5, 9);
<syntaxhighlight lang="algol68">[]REAL data = (3, 1, 4, 1, 5, 9);


PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL:
PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL:
Line 226: Line 316:
sum := 0;
sum := 0;
printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data ))
printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data ))
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 238: Line 328:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
The computation can be written as a generator.
The computation can be written as a generator.
<lang algol68>#!/usr/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# -*- coding: utf-8 -*- #


Line 281: Line 371:
printf(($"SUMSQ GEN: "g(0)l$, SUMSQ GEN data));
printf(($"SUMSQ GEN: "g(0)l$, SUMSQ GEN data));
printf(($"sq SUMMAP GEN: "g(0)l$, ((REAL x)REAL: x*x)SUMMAP GEN data))
printf(($"sq SUMMAP GEN: "g(0)l$, ((REAL x)REAL: x*x)SUMMAP GEN data))
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 293: Line 383:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==

<lang algolw>begin
% procedure to sum the elements of a vector. As the procedure can't find %
===Using a dedicated "sum of squares" procedure===

% the bounds of the array for itself, we pass them in lb and ub %
<syntaxhighlight lang="algolw">begin
% procedure to sum the squares of the elements of a vector. %
% the bounds of the vector must be passed in lb and ub %
real procedure sumSquares ( real array vector ( * )
real procedure sumSquares ( real array vector ( * )
; integer value lb
; integer value lb
Line 312: Line 405:
r_format := "A"; r_w := 10; r_d := 1; % set fixed point output %
r_format := "A"; r_w := 10; r_d := 1; % set fixed point output %
write( sumSquares( numbers, 1, 5 ) );
write( sumSquares( numbers, 1, 5 ) );
end.</lang>
end.</syntaxhighlight>

===Using Jensen's device===
{{Trans|ALGOL60}}
Using the classic [[Jensen's Device]] (first introduced in Algol 60) we can use a generic summation procedure, as in this sample:

<syntaxhighlight lang="algolw">
begin % sum the squares of the elements of a vector, using Jensen's Device %
integer i;
real procedure sum ( integer %name% i; integer value lo, hi; real procedure term );
% i is passed by-name, term is passed as a procedure which makes it effectively passed by-name %
begin
real temp;
temp := 0;
i := lo;
while i <= hi do begin % The Algol W "for" loop (as in Algol 68) creates a distinct %
temp := temp + term; % variable which would not be shared with the passed "i" %
i := i + 1 % Here the actual passed "i" is incremented. %
end while_i_le_temp;
temp
end;
real array A ( 1 :: 5 );
for i := 1 until 5 do A( i ) := i;
r_format := "A"; r_w := 10; r_d := 1; % set fixed point output %
write( sum( i, 1, 5, A( i ) * A( i ) ) );
end.
</syntaxhighlight>


=={{header|Alore}}==
=={{header|Alore}}==


<lang Alore>def sum_squares(a)
<syntaxhighlight lang="alore">def sum_squares(a)
var sum = 0
var sum = 0
for i in a
for i in a
Line 325: Line 444:


WriteLn(sum_squares([3,1,4,1,5,9]))
WriteLn(sum_squares([3,1,4,1,5,9]))
end</lang>
end</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
<lang apl> square_sum←{+/⍵*2}
<syntaxhighlight lang="apl"> square_sum←{+/⍵*2}
square_sum 1 2 3 4 5
square_sum 1 2 3 4 5
55
55
square_sum ⍬ ⍝The empty vector
square_sum ⍬ ⍝The empty vector
0</lang>
0</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==


Two ways of composing a sumOfSquares function:
Two ways of composing a sumOfSquares function:
<lang AppleScript>------ TWO APPROACHES – SUM OVER MAP, AND DIRECT FOLD ----
<syntaxhighlight lang="applescript">------ TWO APPROACHES – SUM OVER MAP, AND DIRECT FOLD ----


-- sumOfSquares :: Num a => [a] -> a
-- sumOfSquares :: Num a => [a] -> a
Line 423: Line 542:
foldl(add, 0, xs)
foldl(add, 0, xs)
end sum</lang>
end sum</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{133.0, 133.0}</lang>
<syntaxhighlight lang="applescript">{133.0, 133.0}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>arr: 1..10
<syntaxhighlight lang="rebol">arr: 1..10


print sum map arr [x][x^2]</lang>
print sum map arr [x][x^2]</syntaxhighlight>


{{out}}
{{out}}
Line 437: Line 556:


=={{header|Astro}}==
=={{header|Astro}}==
<lang python>sum([1, 2, 3, 4]²)</lang>
<syntaxhighlight lang="python">sum([1, 2, 3, 4]²)</syntaxhighlight>

=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">int suma;
int[] a={1, 2, 3, 4, 5, 6};
for(var i : a)
suma = suma + a[i] ^ 2;

write("The sum of squares is: ", suma);</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>list = 3 1 4 1 5 9
<syntaxhighlight lang="autohotkey">list = 3 1 4 1 5 9
Loop, Parse, list, %A_Space%
Loop, Parse, list, %A_Space%
sum += A_LoopField**2
sum += A_LoopField**2
MsgBox,% sum</lang>
MsgBox,% sum</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Vectors are read, space-separated, from stdin; sum of squares goes to stdout. The empty line produces 0.
Vectors are read, space-separated, from stdin; sum of squares goes to stdout. The empty line produces 0.
<lang awk>$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}'
<syntaxhighlight lang="awk">$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}'
3 1 4 1 5 9
3 1 4 1 5 9
133
133


0</lang>
0</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
{{works with|QBasic}}
Assume the numbers are in an array called <code>a</code>.
Assume the numbers are in an array called <code>a</code>.
<lang qbasic>sum = 0
<syntaxhighlight lang="qbasic">sum = 0
FOR I = LBOUND(a) TO UBOUND(a)
FOR I = LBOUND(a) TO UBOUND(a)
sum = sum + a(I) ^ 2
sum = sum + a(I) ^ 2
NEXT I
NEXT I
PRINT "The sum of squares is: " + sum</lang>
PRINT "The sum of squares is: " + sum</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang freebasic>' Sum of squares
<syntaxhighlight lang="freebasic">' Sum of squares
FUNCTION ss(int arr[], NUMBER elem)
FUNCTION ss(int arr[], NUMBER elem)
sum = 0
sum = 0
Line 484: Line 612:
vector[i] = i + 1
vector[i] = i + 1
NEXT
NEXT
PRINT ss(vector, elem)</lang>
PRINT ss(vector, elem)</syntaxhighlight>


{{out}}
{{out}}
Line 491: Line 619:
prompt$ ./sumsquares -s 1000
prompt$ ./sumsquares -s 1000
333833500</pre>
333833500</pre>

==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">arraybase 1

dim a(6)
a[1] = 1.0
a[2] = 2.0
a[3] = 3.0
a[4] = -1.0
a[5] = -2.0
a[6] = -3.0

sum = 0
for i = 1 to a[?]
sum += a[i] ^ 2
next i
print "The sum of squares is: "; sum
end</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
BBC BASIC cannot have a zero-length array.
BBC BASIC cannot have a zero-length array.
<lang bbcbasic> DIM vector(5)
<syntaxhighlight lang="bbcbasic"> DIM vector(5)
vector() = 1, 2, 3, 4, 5, 6
vector() = 1, 2, 3, 4, 5, 6
PRINT "Sum of squares = " ; MOD(vector()) ^ 2</lang>
PRINT "Sum of squares = " ; MOD(vector()) ^ 2</syntaxhighlight>
{{out}}
{{out}}
<pre>Sum of squares = 91</pre>
<pre>Sum of squares = 91</pre>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 INPUT PROMPT "Number of elements: ":N
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "Number of elements: ":N
110 NUMERIC A(1 TO N)
110 NUMERIC A(1 TO N)
120 FOR I=1 TO N
120 FOR I=1 TO N
Line 514: Line 660:
200 NEXT
200 NEXT
210 LET SQ=S
210 LET SQ=S
220 END DEF</lang>
220 END DEF</syntaxhighlight>

==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">data 1.0, 2.0, 3.0, -1.0, -2.0, -3.0
dim a(5)
sum = 0

for i = 0 to arraysize(a(), 1)
read a(i)
sum = sum + a(i) ^ 2
next i
print "The sum of squares is: ", sum
end</syntaxhighlight>


=={{header|bc}}==
=={{header|bc}}==
<lang bc>define s(a[], n) {
<syntaxhighlight lang="bc">define s(a[], n) {
auto i, s
auto i, s
Line 525: Line 683:
return(s)
return(s)
}</lang>
}</syntaxhighlight>

=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"

let sumsquares(v, len) =
len=0 -> 0,
!v * !v + sumsquares(v+1, len-1)
let start() be
$( let vector = table 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
writef("%N*N", sumsquares(vector, 10))
$)</syntaxhighlight>
{{out}}
<pre>385</pre>

=={{header|BQN}}==
Similar to the BQN entry in [[Sum of a series]].
<syntaxhighlight lang="bqn">SSq ← +´√⁼


•Show SSq 1‿2‿3‿4‿5
•Show SSq ⟨⟩</syntaxhighlight>
<syntaxhighlight lang="text">55
0</syntaxhighlight>
=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( sumOfSquares
<syntaxhighlight lang="bracmat">( ( sumOfSquares
= sum component
= sum component
. 0:?sum
. 0:?sum
Line 540: Line 720:
& out$(sumOfSquares$(3 4 i*5))
& out$(sumOfSquares$(3 4 i*5))
& out$(sumOfSquares$(a b c))
& out$(sumOfSquares$(a b c))
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>25
<pre>25
Line 547: Line 727:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 } #Prints 385</lang>
<syntaxhighlight lang="brat">p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 } #Prints 385</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


double squaredsum(double *l, int e)
double squaredsum(double *l, int e)
Line 569: Line 749:
printf("%lf\n", squaredsum(NULL, 0));
printf("%lf\n", squaredsum(NULL, 0));
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 589: Line 769:
Console.WriteLine(SumOfSquares(new int[] { })); // 0
Console.WriteLine(SumOfSquares(new int[] { })); // 0
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
===Using accumulate===
===Using accumulate===
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
#include <numeric>
#include <vector>
#include <vector>
Line 618: Line 798:
std::cout << vec_add_squares(v) << std::endl;
std::cout << vec_add_squares(v) << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>
===Using inner_product===
===Using inner_product===
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
#include <numeric>
#include <vector>
#include <vector>
Line 635: Line 815:
std::cout << std::inner_product(begin(v), end(v), begin(v), 0.0) << std::endl;
std::cout << std::inner_product(begin(v), end(v), begin(v), 0.0) << std::endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


===Using Boost.Lambda===
===Using Boost.Lambda===
{{libheader|Boost.Lambda}}
{{libheader|Boost.Lambda}}
<lang cpp>#include <numeric>
<syntaxhighlight lang="cpp">#include <numeric>
#include <vector>
#include <vector>
#include "boost/lambda/lambda.hpp"
#include "boost/lambda/lambda.hpp"
Line 648: Line 828:


return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2);
return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2);
}</lang>
}</syntaxhighlight>


=={{header|Chef}}==
=={{header|Chef}}==
<lang Chef>Sum of squares.
<syntaxhighlight lang="chef">Sum of squares.


First input is length of vector, then rest of input is vector.
First input is length of vector, then rest of input is vector.
Line 673: Line 853:
Serves 1.
Serves 1.


</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn sum-of-squares [v]
<syntaxhighlight lang="clojure">(defn sum-of-squares [v]
(reduce #(+ %1 (* %2 %2)) 0 v))</lang>
(reduce #(+ %1 (* %2 %2)) 0 v))</syntaxhighlight>

=={{header|CLU}}==
<syntaxhighlight lang="clu">sum_squares = proc (ns: sequence[int]) returns (int)
sum: int := 0
for n: int in sequence[int]$elements(ns) do
sum := sum + n ** 2
end
return(sum)
end sum_squares

start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, int$unparse(sum_squares(sequence[int]$[])))
stream$putl(po, int$unparse(sum_squares(sequence[int]$[1,2,3,4,5])))
stream$putl(po, int$unparse(sum_squares(sequence[int]$[42])))
end start_up</syntaxhighlight>
{{out}}
<pre>0
55
1764</pre>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
sumOfSquares = ( list ) ->
sumOfSquares = ( list ) ->
list.reduce (( sum, x ) -> sum + ( x * x )), 0
list.reduce (( sum, x ) -> sum + ( x * x )), 0
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defun sum-of-squares (vector)
<syntaxhighlight lang="lisp">(defun sum-of-squares (vector)
(loop for x across vector sum (expt x 2)))</lang>
(loop for x across vector sum (expt x 2)))</syntaxhighlight>

Or in a functional way:
<syntaxhighlight lang="lisp">(defun sum-of-squares (vec)
(reduce #'+ (map 'vector (lambda (x) (* x x)) vec)))</syntaxhighlight>


=={{header|Cowgol}}==
=={{header|Cowgol}}==


<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
include "argv.coh";


Line 727: Line 932:
# Print sum of squares of numbers
# Print sum of squares of numbers
print_i32(sumsquare(&nums[0], len as intptr));
print_i32(sumsquare(&nums[0], len as intptr));
print_nl();</lang>
print_nl();</syntaxhighlight>


{{out}}
{{out}}
Line 740: Line 945:
=={{header|Crystal}}==
=={{header|Crystal}}==


<syntaxhighlight lang="ruby">
<lang Ruby>
def sum_squares(a)
def sum_squares(a)
a.map{|e| e*e}.sum()
a.map{|e| e*e}.sum()
Line 747: Line 952:
puts sum_squares([1, 2, 3])
puts sum_squares([1, 2, 3])
# => 14
# => 14
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
===Iterative Version===
===Iterative Version===
<lang d>T sumSquares(T)(T[] a) pure nothrow @safe @nogc {
<syntaxhighlight lang="d">T sumSquares(T)(T[] a) pure nothrow @safe @nogc {
T sum = 0;
T sum = 0;
foreach (e; a)
foreach (e; a)
Line 762: Line 967:


[3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln;
[3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>133.61</pre>
<pre>133.61</pre>


===Polymorphic Functional Style===
===Polymorphic Functional Style===
<lang d>import std.stdio, std.algorithm, std.traits, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.traits, std.range;


auto sumSquares(Range)(Range data) pure nothrow @safe @nogc {
auto sumSquares(Range)(Range data) pure nothrow @safe @nogc {
Line 777: Line 982:
items.sumSquares.writeln;
items.sumSquares.writeln;
10.iota.sumSquares.writeln;
10.iota.sumSquares.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>133.61
<pre>133.61
Line 784: Line 989:
=={{header|Dart}}==
=={{header|Dart}}==
===Iterative Version===
===Iterative Version===
<lang d>sumOfSquares(list) {
<syntaxhighlight lang="d">sumOfSquares(list) {
var sum=0;
var sum=0;
list.forEach((var n) { sum+=(n*n); });
list.forEach((var n) { sum+=(n*n); });
Line 794: Line 999:
print(sumOfSquares([1,2,3]));
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
print(sumOfSquares([10]));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 801: Line 1,006:


===Functional Style Version===
===Functional Style Version===
<lang d>num sumOfSquares(List<num> l) => l.map((num x)=>x*x)
<syntaxhighlight lang="d">num sumOfSquares(List<num> l) => l.map((num x)=>x*x)
.fold(0, (num p,num n)=> p + n);
.fold(0, (num p,num n)=> p + n);


Line 808: Line 1,013:
print(sumOfSquares([1,2,3]));
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
print(sumOfSquares([10]));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 816: Line 1,021:
=={{header|Delphi}}==
=={{header|Delphi}}==
Delphi has standard SumOfSquares function in Math unit:
Delphi has standard SumOfSquares function in Math unit:
<lang Delphi>program SumOfSq;
<syntaxhighlight lang="delphi">program SumOfSq;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 836: Line 1,041:
Writeln(SumOfSquares(A):6:2); // 30.00
Writeln(SumOfSquares(A):6:2); // 30.00
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>

=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec sum_squares([*] int arr) ulong:
ulong sum, item;
word i, len;
sum := 0;
len := dim(arr,1);
if len>0 then
for i from 0 upto len-1 do
item := |arr[i];
sum := sum + item * item
od
fi;
sum
corp

proc nonrec main() void:
type A0 = [0] int,
A1 = [1] int,
A5 = [5] int;
writeln(sum_squares(A0()));
writeln(sum_squares(A1(42)));
writeln(sum_squares(A5(1,2,3,4,5)))
corp</syntaxhighlight>
{{out}}
<pre>0
1764
55</pre>


=={{header|E}}==
=={{header|E}}==


<lang e>def sumOfSquares(numbers) {
<syntaxhighlight lang="e">def sumOfSquares(numbers) {
var sum := 0
var sum := 0
for x in numbers {
for x in numbers {
Line 846: Line 1,080:
}
}
return sum
return sum
}</lang>
}</syntaxhighlight>

=={{header|EasyLang}}==

<syntaxhighlight lang="easylang">
nums[] = [ 1 2 3 4 5 ]
for v in nums[]
sum += v * v
.
print sum
</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==


<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 882: Line 1,126:


end
end
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 6.x :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
SumOfSquares(list)
SumOfSquares(list)
= list.selectBy:(x => x * x).summarize(new Integer());
= list.selectBy::(x => x * x).summarize(new Integer());
public program()
public program()
Line 898: Line 1,142:
.printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5}))
.printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5}))
.printLine(SumOfSquares(Array.MinValue))
.printLine(SumOfSquares(Array.MinValue))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 907: Line 1,151:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end)
<syntaxhighlight lang="elixir">iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end)
133</lang>
133</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun sum-of-squares (numbers)
<lang Emacs Lisp>
(apply #'+ (mapcar (lambda (k) (* k k)) numbers)))
(defun sum-square (ls)
(apply '+ (mapcar (lambda (k) (* k k) ) ls) ))


(insert (format "%d"(sum-square (number-sequence 0 3) )))
(sum-of-squares (number-sequence 0 3)) ;=> 14</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
14
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).</lang>
<syntaxhighlight lang="erlang">lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).</syntaxhighlight>

=={{header|Euler}}==
Using [[Jensen's Device]]
'''begin'''
'''new''' i; '''new''' A; '''new''' sum;
sum &lt;- ` '''formal''' i; '''formal''' lo; '''formal''' hi; '''formal''' term;
'''begin'''
'''new''' temp; '''label''' loop;
temp &lt;- 0;
i &lt;- lo;
loop: '''begin'''
temp &lt;- temp + term;
'''if''' [ i &lt;- i + 1 ] &lt;= hi '''then''' '''goto''' loop '''else''' 0
'''end''';
temp
'''end'''
&apos;;
A &lt;- ( 1, 2, 3, 4, 5 );
'''out''' sum( @i, 1, '''length''' A, `A[i]*A[i]&apos; )
'''end''' $


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function SumOfSquares(sequence v)
<syntaxhighlight lang="euphoria">function SumOfSquares(sequence v)
atom sum
atom sum
sum = 0
sum = 0
Line 933: Line 1,192:
end for
end for
return sum
return sum
end function</lang>
end function</syntaxhighlight>


=={{header|Excel}}==
=={{header|Excel}}==
To find the sum of squares of values from A1 to A10, type in any other cell :
To find the sum of squares of values from A1 to A10, type in any other cell :


<syntaxhighlight lang="excel">
<lang Excel>
=SUMSQ(A1:A10)
=SUMSQ(A1:A10)
</syntaxhighlight>
</lang>


The above expression will return zero if there are no values in any cell.
The above expression will return zero if there are no values in any cell.


<lang>
<syntaxhighlight lang="text">
12 3 5 23 13 67 15 9 4 2
12 3 5 23 13 67 15 9 4 2
5691
5691
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>[1 .. 10] |> List.fold (fun a x -> a + x * x) 0
<syntaxhighlight lang="fsharp">[1 .. 10] |> List.fold (fun a x -> a + x * x) 0
[|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 0</lang>
[|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: math sequences ;
<syntaxhighlight lang="factor">USE: math sequences ;


: sum-of-squares ( seq -- n ) [ sq ] map-sum ;
: sum-of-squares ( seq -- n ) [ sq ] map-sum ;


{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares</lang>
{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares</syntaxhighlight>


=={{header|FALSE}}==
=={{header|FALSE}}==
<syntaxhighlight lang="false">
<lang FALSE>
0 3 1 4 1 5 9$*\ [$0=~][$*+\]#%.
0 3 1 4 1 5 9$*\ [$0=~][$*+\]#%.
</syntaxhighlight>
</lang>


=={{header|Fantom}}==
=={{header|Fantom}}==
<lang fantom>
<syntaxhighlight lang="fantom">
class SumSquares
class SumSquares
{
{
Line 985: Line 1,244:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Fish}}==
=={{header|Fish}}==
<syntaxhighlight lang="fish">v
<lang Fish>v
\0&
\0&
>l?!v:*&+&
>l?!v:*&+&
>&n;</lang>
>&n;</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: fsum**2 ( addr n -- f )
<syntaxhighlight lang="forth">: fsum**2 ( addr n -- f )
0e
0e
dup 0= if 2drop exit then
dup 0= if 2drop exit then
Line 1,002: Line 1,261:


create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fsum**2 f. \ 133.</lang>
test 6 fsum**2 f. \ 133.</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic:
In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic:
<lang fortran>real, dimension(1000) :: a = (/ (i, i=1, 1000) /)
<syntaxhighlight lang="fortran">real, dimension(1000) :: a = (/ (i, i=1, 1000) /)
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real :: result, zresult
real :: result, zresult
Line 1,014: Line 1,273:
result = sum(a**2) ! Use exponentiation operator to get squares
result = sum(a**2) ! Use exponentiation operator to get squares


zresult = sum(p*p) ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected</lang>
zresult = sum(p*p) ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function SumSquares(a() As Double) As Double
Function SumSquares(a() As Double) As Double
Line 1,034: Line 1,293:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,042: Line 1,301:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
f = {|x| x^2} // Anonymous function which squares its argument
f = {|x| x^2} // Anonymous function which squares its argument
a = [1,2,3,5,7]
a = [1,2,3,5,7]
println[sum[map[f,a], 0]]
println[sum[map[f,a], 0]]
</syntaxhighlight>
</lang>


=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


In [https://wiki.formulae.org/Sum_of_squares this] page you can see the solution of this task.
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sum_of_squares}}


'''Solution'''
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.


[[File:Fōrmulæ - Sum of squares 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.

'''Test cases'''

[[File:Fōrmulæ - Sum of squares 02.png]]

[[File:Fōrmulæ - Sum of squares 03.png]]

[[File:Fōrmulæ - Sum of squares 04.png]]

[[File:Fōrmulæ - Sum of squares 05.png]]

[[File:Fōrmulæ - Sum of squares 06.png]]

[[File:Fōrmulæ - Sum of squares 07.png]]


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Just multiplying a vector by itself yields the sum of squares (it's an inner product)
<syntaxhighlight lang="gap"># Just multiplying a vector by itself yields the sum of squares (it's an inner product)
# It's necessary to check for the empty vector though
# It's necessary to check for the empty vector though
SumSq := function(v)
SumSq := function(v)
Line 1,065: Line 1,338:
return v*v;
return v*v;
fi;
fi;
end;</lang>
end;</syntaxhighlight>


=={{header|GEORGE}}==
=={{header|GEORGE}}==
<lang GEORGE>read (n) print ;
<syntaxhighlight lang="george">read (n) print ;
0
0
1, n rep (i)
1, n rep (i)
read print dup mult +
read print dup mult +
]
]
print</lang>
print</syntaxhighlight>
data
data
<pre>
<pre>
Line 1,108: Line 1,381:
=={{header|Go}}==
=={{header|Go}}==
;Implementation
;Implementation
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,120: Line 1,393:
}
}
fmt.Println(sum)
fmt.Println(sum)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,126: Line 1,399:
</pre>
</pre>
;Library
;Library
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,138: Line 1,411:
func main() {
func main() {
fmt.Println(floats.Dot(v, v))
fmt.Println(floats.Dot(v, v))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,145: Line 1,418:


=={{header|Golfscript}}==
=={{header|Golfscript}}==
<lang golfscript>{0\{.*+}%}:sqsum;
<syntaxhighlight lang="golfscript">{0\{.*+}%}:sqsum;
# usage example
# usage example
[1 2 3]sqsum puts</lang>
[1 2 3]sqsum puts</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def array = 1..3
<syntaxhighlight lang="groovy">def array = 1..3


// square via multiplication
// square via multiplication
Line 1,159: Line 1,432:
sumSq = array.collect { it ** 2 }.sum()
sumSq = array.collect { it ** 2 }.sum()


println sumSq</lang>
println sumSq</syntaxhighlight>


{{out}}
{{out}}
Line 1,167: Line 1,440:
=={{header|Haskell}}==
=={{header|Haskell}}==
Three approaches:
Three approaches:
<lang haskell>versions :: [[Int] -> Int]
<syntaxhighlight lang="haskell">versions :: [[Int] -> Int]
versions =
versions =
[ sum . fmap (^ 2) -- ver 1
[ sum . fmap (^ 2) -- ver 1
Line 1,176: Line 1,449:
main :: IO ()
main :: IO ()
main =
main =
mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions)</lang>
mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[133,91,0,1]
<pre>[133,91,0,1]
Line 1,183: Line 1,456:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
local lst
local lst
lst := []
lst := []
Line 1,196: Line 1,469:
every total +:= !lst ^ 2
every total +:= !lst ^ 2
return total
return total
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==


<lang idl>print,total(array^2)</lang>
<syntaxhighlight lang="idl">print,total(array^2)</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
<lang inform7>Sum Of Squares is a room.
<syntaxhighlight lang="inform7">Sum Of Squares is a room.


To decide which number is the sum of (N - number) and (M - number) (this is summing):
To decide which number is the sum of (N - number) and (M - number) (this is summing):
Line 1,218: Line 1,491:
say line break;
say line break;
say the sum of squares of {1, 2, 3};
say the sum of squares of {1, 2, 3};
end the story.</lang>
end the story.</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang io>list(3,1,4,1,5,9) map(squared) sum</lang>
<syntaxhighlight lang="io">list(3,1,4,1,5,9) map(squared) sum</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


<lang j>ss=: +/ @: *:</lang>
<syntaxhighlight lang="j">ss=: +/ @: *:</syntaxhighlight>


That is, sum composed with square. The verb also works on higher-ranked arrays. For example:
That is, sum composed with square. The verb also works on higher-ranked arrays. For example:


<lang j> ss 3 1 4 1 5 9
<syntaxhighlight lang="j"> ss 3 1 4 1 5 9
133
133
ss $0 NB. $0 is a zero-length vector
ss $0 NB. $0 is a zero-length vector
Line 1,235: Line 1,508:
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers
ss x
ss x
9.09516 5.19512 5.84173 6.6916</lang>
9.09516 5.19512 5.84173 6.6916</syntaxhighlight>


The computation can also be written as a loop. It is shown here for comparison only and
The computation can also be written as a loop. It is shown here for comparison only and
is highly non-preferred compared to the version above.
is highly non-preferred compared to the version above.


<lang j>ss1=: 3 : 0
<syntaxhighlight lang="j">ss1=: 3 : 0
z=. 0
z=. 0
for_i. i.#y do. z=. z+*:i{y end.
for_i. i.#y do. z=. z+*:i{y end.
Line 1,250: Line 1,523:
0
0
ss1 x
ss1 x
9.09516 5.19512 5.84173 6.6916</lang>
9.09516 5.19512 5.84173 6.6916</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>public class SumSquares
<syntaxhighlight lang="java5">public class SumSquares
{
{
public static void main(final String[] args)
public static void main(final String[] args)
Line 1,264: Line 1,537:
System.out.println("The sum of the squares is: " + sum);
System.out.println("The sum of the squares is: " + sum);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===ES5===
===ES5===
<lang javascript>function sumsq(array) {
<syntaxhighlight lang="javascript">function sumsq(array) {
var sum = 0;
var sum = 0;
var i, iLen;
var i, iLen;
Line 1,278: Line 1,551:
}
}


alert(sumsq([1,2,3,4,5])); // 55</lang>
alert(sumsq([1,2,3,4,5])); // 55</syntaxhighlight>


An alternative using a while loop and Math.pow
An alternative using a while loop and Math.pow


<lang javascript>function sumsq(array) {
<syntaxhighlight lang="javascript">function sumsq(array) {
var sum = 0,
var sum = 0,
i = array.length;
i = array.length;
Line 1,291: Line 1,564:
}
}


alert(sumsq([1,2,3,4,5])); // 55</lang>
alert(sumsq([1,2,3,4,5])); // 55</syntaxhighlight>




{{libheader|Functional}}<lang javascript>Functional.reduce("x+y*y", 0, [1,2,3,4,5])</lang>
{{libheader|Functional}}<syntaxhighlight lang="javascript">Functional.reduce("x+y*y", 0, [1,2,3,4,5])</syntaxhighlight>


map (JS 1.6) and reduce (JS 1.8)
map (JS 1.6) and reduce (JS 1.8)


<lang javascript>[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; });</lang>
<syntaxhighlight lang="javascript">[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; });</syntaxhighlight>


===ES6===
===ES6===


Two ways of composing a sumOfSquares function
Two ways of composing a sumOfSquares function
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,337: Line 1,610:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>133
<pre>133
133</pre>
133</pre>

=={{header|Joy}}==
<syntaxhighlight lang="joy">[1 2 3 4 5] 0 [dup * +] fold.</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
jq supports both arrays and streams, and so we illustrate how to handle both.
jq supports both arrays and streams, and so we illustrate how to handle both.
<lang jq># ss for an input array:
<syntaxhighlight lang="jq"># ss for an input array:
def ss: map(.*.) | add;
def ss: map(.*.) | add;


# ss for a stream, S, without creating an intermediate array:
# ss for a stream, S, without creating an intermediate array:
def ss(S): reduce S as $x (0; . + ($x * $x) );</lang>We can also use a generic "SIGMA" filter that behaves like the mathematical SIGMA:<lang jq>
def ss(S): reduce S as $x (0; . + ($x * $x) );</syntaxhighlight>We can also use a generic "SIGMA" filter that behaves like the mathematical SIGMA:<syntaxhighlight lang="jq">
# SIGMA(exp) computes the sum of exp over the input array:
# SIGMA(exp) computes the sum of exp over the input array:
def SIGMA(exp): map(exp) | add;
def SIGMA(exp): map(exp) | add;
Line 1,354: Line 1,630:
# SIGMA(exp; S) computes the sum of exp over elements of the stream, S,
# SIGMA(exp; S) computes the sum of exp over elements of the stream, S,
# without creating an intermediate array:
# without creating an intermediate array:
def SIGMA(exp; S): reduce (S|exp) as $x (0; . + $x);</lang>
def SIGMA(exp; S): reduce (S|exp) as $x (0; . + $x);</syntaxhighlight>
Finally, a "mapreduce" filter:<lang jq>
Finally, a "mapreduce" filter:<syntaxhighlight lang="jq">
def mapreduce(mapper; reducer; zero):
def mapreduce(mapper; reducer; zero):
if length == 0 then zero
if length == 0 then zero
else map(mapper) | reducer
else map(mapper) | reducer
end;
end;
</syntaxhighlight>
</lang>
Demonstration:<lang jq>def demo(n):
Demonstration:<syntaxhighlight lang="jq">def demo(n):
"ss: \( [range(0;n)] | ss )",
"ss: \( [range(0;n)] | ss )",
"ss(S): \( ss( range(0;n) ) )",
"ss(S): \( ss( range(0;n) ) )",
Line 1,369: Line 1,645:
;
;


demo(3) # 0^2 + 1^2 + 2^2</lang>
demo(3) # 0^2 + 1^2 + 2^2</syntaxhighlight>
{{out}}
{{out}}
<lang jq>"ss: 5"
<syntaxhighlight lang="jq">"ss: 5"
"ss(S): 5"
"ss(S): 5"
"SIGMA(.*.): 5"
"SIGMA(.*.): 5"
"SIGMA(.*.;S): 5"
"SIGMA(.*.;S): 5"
"mapreduce(.*.; add; 0): 5"</lang>
"mapreduce(.*.; add; 0): 5"</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
There are several easy ways to do this in Julia:
There are several easy ways to do this in Julia:
<lang julia>julia> sum([1,2,3,4,5].^2)
<syntaxhighlight lang="julia">julia> sum([1,2,3,4,5].^2)
55
55


Line 1,389: Line 1,665:


julia> sum([x^2 for x in []])
julia> sum([x^2 for x in []])
0</lang>
0</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
<syntaxhighlight lang="k">
<lang k>
ss: {+/x*x}
ss: {+/x*x}
ss 1 2 3 4 5
ss 1 2 3 4 5
Line 1,398: Line 1,674:
ss@!0
ss@!0
0
0
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 1,409: Line 1,685:
Finally, a classic for-loop can also be used. Note that because <code>forEach</code> and <code>fold</code> are inline functions, these are actually exactly as efficient as the had-written for-loop.
Finally, a classic for-loop can also be used. Note that because <code>forEach</code> and <code>fold</code> are inline functions, these are actually exactly as efficient as the had-written for-loop.


<lang kotlin>import kotlin.random.Random
<syntaxhighlight lang="kotlin">import kotlin.random.Random
import kotlin.system.measureTimeMillis
import kotlin.system.measureTimeMillis
import kotlin.time.milliseconds
import kotlin.time.milliseconds
Line 1,460: Line 1,736:
for (v in longArray) acc += v
for (v in longArray) acc += v
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,487: Line 1,763:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def sumsq
{def sumsq
{lambda {:s}
{lambda {:s}
Line 1,497: Line 1,773:
{sumsq 0}
{sumsq 0}
-> 0
-> 0
</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>[1 2 3 4 5] 2 ** '+ reduce .</lang>
<syntaxhighlight lang="lang5">[1 2 3 4 5] 2 ** '+ reduce .</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define sumofsquares(values::array) => {
<syntaxhighlight lang="lasso">define sumofsquares(values::array) => {


local(sum = 0)
local(sum = 0)
Line 1,514: Line 1,790:
}
}


sumofsquares(array(1,2,3,4,5))</lang>
sumofsquares(array(1,2,3,4,5))</syntaxhighlight>
{{out}}
{{out}}
<pre>55</pre>
<pre>55</pre>


=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(defun sum-sq (nums)
(defun sum-sq (nums)
(lists:foldl
(lists:foldl
Line 1,525: Line 1,801:
(+ acc (* x x)))
(+ acc (* x x)))
0 nums))
0 nums))
</syntaxhighlight>
</lang>


Usage:
Usage:
<lang lisp>
<syntaxhighlight lang="lisp">
> (sum-sq '(3 1 4 1 5 9))
> (sum-sq '(3 1 4 1 5 9))
133
133
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>' [RC] Sum of Squares
<syntaxhighlight lang="lb">' [RC] Sum of Squares


SourceList$ ="3 1 4 1 5 9"
SourceList$ ="3 1 4 1 5 9"
Line 1,560: Line 1,836:
print "Sum of squares is "; SumOfSquares
print "Sum of squares is "; SumOfSquares


end</lang>
end</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>put "1,2,3,4,5" into nums
<syntaxhighlight lang="livecode">put "1,2,3,4,5" into nums
repeat for each item n in nums
repeat for each item n in nums
add (n * n) to m
add (n * n) to m
end repeat
end repeat
put m // 55</lang>
put m // 55</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>print apply "sum map [? * ?] [1 2 3 4 5] ; 55</lang>
<syntaxhighlight lang="logo">print apply "sum map [? * ?] [1 2 3 4 5] ; 55</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<lang logtalk>sum(List, Sum) :-
<syntaxhighlight lang="logtalk">sum(List, Sum) :-
sum(List, 0, Sum).
sum(List, 0, Sum).


Line 1,579: Line 1,855:
sum([X| Xs], Acc, Sum) :-
sum([X| Xs], Acc, Sum) :-
Acc2 is Acc + X,
Acc2 is Acc + X,
sum(Xs, Acc2, Sum).</lang>
sum(Xs, Acc2, Sum).</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end
<syntaxhighlight lang="lua">function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end
function squaresumt(t) return squaresum(unpack(t)) end
function squaresumt(t) return squaresum(unpack(t)) end


print(squaresumt{3, 5, 4, 1, 7})</lang>
print(squaresumt{3, 5, 4, 1, 7})</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
M2000 use two concepts for arrays: standard array like A() and pointer to array as A. Pointer arithmetic not allowed here. Standard arrays are values types, and pointers are reference types. So we can handle an array both with pointer and without.
M2000 use two concepts for arrays: standard array like A() and pointer to array as A. Pointer arithmetic not allowed here. Standard arrays are values types, and pointers are reference types. So we can handle an array both with pointer and without.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Dim A() 'make an array with zero items
Dim A() 'make an array with zero items


Line 1,617: Line 1,893:
Now A and A() prints a 20 item array (Cons() add a list of arrays)
Now A and A() prints a 20 item array (Cons() add a list of arrays)
Print A ' or Print A() print the same
Print A ' or Print A() print the same
</syntaxhighlight>
</lang>


And this is the task, using a lambda function (we can use a standard function, just use Function Square { code here })
And this is the task, using a lambda function (we can use a standard function, just use Function Square { code here })
Line 1,625: Line 1,901:
When we pass an array in stack, a pointer to array (to one of two interfaces) and depends the name type of a read to make this a copy or a pointer to array. So here we use: read a as a pointer to array (so it is a by reference pass). We can use Read a() and then a=a() (and remove Link a to a()), so we use by value pass, and that is a decision from callee, not the caller (this happen for objects)
When we pass an array in stack, a pointer to array (to one of two interfaces) and depends the name type of a read to make this a copy or a pointer to array. So here we use: read a as a pointer to array (so it is a by reference pass). We can use Read a() and then a=a() (and remove Link a to a()), so we use by value pass, and that is a decision from callee, not the caller (this happen for objects)


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
A=(1,2,3,4,5)
A=(1,2,3,4,5)
Line 1,647: Line 1,923:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
F := V -> add(v^2, v in V):
F := V -> add(v^2, v in V):
F(<1,2,3,4,5>);
F(<1,2,3,4,5>);
</syntaxhighlight>
</lang>


=={{header|Mathematica}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
As a function 1:
As a function 1:
<lang mathematica>SumOfSquares[x_]:=Total[x^2]
<syntaxhighlight lang="mathematica">SumOfSquares[x_]:=Total[x^2]
SumOfSquares[{1,2,3,4,5}]</lang>
SumOfSquares[{1,2,3,4,5}]</syntaxhighlight>
As a function 2:
As a function 2:
<lang mathematica>SumOfSquares[x_]:=x.x
<syntaxhighlight lang="mathematica">SumOfSquares[x_]:=x.x
SumOfSquares[{1,2,3,4,5}]</lang>
SumOfSquares[{1,2,3,4,5}]</syntaxhighlight>
Pure function 1: (postfix operator in the following examples)
Pure function 1: (postfix operator in the following examples)
<lang mathematica>{1,2,3,4,5} // Total[#^2] &</lang>
<syntaxhighlight lang="mathematica">{1,2,3,4,5} // Total[#^2] &</syntaxhighlight>
Pure function 2:
Pure function 2:
<lang mathematica>{1, 2, 3, 4, 5} // #^2 & // Total</lang>
<syntaxhighlight lang="mathematica">{1, 2, 3, 4, 5} // #^2 & // Total</syntaxhighlight>
Pure function 3:
Pure function 3:
<lang mathematica>{1, 2, 3, 4, 5} // #.#&</lang>
<syntaxhighlight lang="mathematica">{1, 2, 3, 4, 5} // #.#&</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang Matlab>function [squaredSum] = sumofsquares(inputVector)
<syntaxhighlight lang="matlab">function [squaredSum] = sumofsquares(inputVector)
squaredSum = sum( inputVector.^2 );</lang>
squaredSum = sum( inputVector.^2 );</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>nums : [3,1,4,1,5,9];
<syntaxhighlight lang="maxima">nums : [3,1,4,1,5,9];
sum(nums[i]^2,i,1,length(nums));</lang>
sum(nums[i]^2,i,1,length(nums));</syntaxhighlight>
or
or
<lang maxima>nums : [3,1,4,1,5,9];
<syntaxhighlight lang="maxima">nums : [3,1,4,1,5,9];
lsum(el^2, el, nums);</lang>
lsum(el^2, el, nums);</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang>
<syntaxhighlight lang="text">
:- module sum_of_squares.
:- module sum_of_squares.
:- interface.
:- interface.
Line 1,698: Line 1,974:


sum_of_squares(Ns) = list.foldl((func(N, Acc) = Acc + N * N), Ns, 0).
sum_of_squares(Ns) = list.foldl((func(N, Acc) = Acc + N * N), Ns, 0).
</syntaxhighlight>
</lang>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>((bool) ((dup *) (+) map-reduce) (pop 0) if) :sq-sum
<syntaxhighlight lang="min">((bool) ((dup *) (+) map-reduce) (pop 0) if) :sq-sum


(1 2 3 4 5) sq-sum puts
(1 2 3 4 5) sq-sum puts
() sq-sum puts</lang>
() sq-sum puts</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,713: Line 1,989:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>sumOfSquares = function(seq)
<syntaxhighlight lang="miniscript">sumOfSquares = function(seq)
sum = 0
sum = 0
for item in seq
for item in seq
Line 1,723: Line 1,999:
print sumOfSquares([4, 8, 15, 16, 23, 42])
print sumOfSquares([4, 8, 15, 16, 23, 42])
print sumOfSquares([1, 2, 3, 4, 5])
print sumOfSquares([1, 2, 3, 4, 5])
print sumOfSquares([])</lang>
print sumOfSquares([])</syntaxhighlight>
{{out}}
{{out}}
<pre>2854
<pre>2854
Line 1,730: Line 2,006:


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>x^2 + С/П БП 00</lang>
<syntaxhighlight lang="text">x^2 + С/П БП 00</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE SumSquares EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE SumSquares EXPORTS Main;


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 1,751: Line 2,027:
IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0})));
IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0})));
IO.Put("\n");
IO.Put("\n");
END SumSquares.</lang>
END SumSquares.</syntaxhighlight>


=={{header|MOO}}==
=={{header|MOO}}==
<lang moo>@verb #100:sum_squares this none this rd
<syntaxhighlight lang="moo">@verb #100:sum_squares this none this rd
@program #100:sum_squares
@program #100:sum_squares
sum = 0;
sum = 0;
Line 1,769: Line 2,045:
;#100:sum_squares({})
;#100:sum_squares({})
{} => 0
{} => 0
</syntaxhighlight>
</lang>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>SUMSQUARE(X)
<syntaxhighlight lang="mumps">SUMSQUARE(X)
;X is assumed to be a list of numbers separated by "^"
;X is assumed to be a list of numbers separated by "^"
NEW RESULT,I
NEW RESULT,I
SET RESULT=0,I=1
SET RESULT=0,I=1
FOR QUIT:(I>$LENGTH(X,"^")) SET RESULT=($PIECE(X,"^",I)*$PIECE(X,"^",I))+RESULT,I=I+1
FOR QUIT:(I>$LENGTH(X,"^")) SET RESULT=($PIECE(X,"^",I)*$PIECE(X,"^",I))+RESULT,I=I+1
QUIT RESULT</lang>
QUIT RESULT</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang nanoquery>def sum_squares(vector)
<syntaxhighlight lang="nanoquery">def sum_squares(vector)
if len(vector) = 0
if len(vector) = 0
return 0
return 0
Line 1,794: Line 2,070:
println sum_squares({})
println sum_squares({})
println sum_squares({1, 2, 3, 4, 5})
println sum_squares({1, 2, 3, 4, 5})
println sum_squares({10, 3456, 2, 6})</lang>
println sum_squares({10, 3456, 2, 6})</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 1,801: Line 2,077:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>SS(x : list[double]) : double
<syntaxhighlight lang="nemerle">SS(x : list[double]) : double
{
{
|[] => 0.0
|[] => 0.0
|_ => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_)
|_ => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_)
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang netrexx>/*NetRexx *************************************************************
<syntaxhighlight lang="netrexx">/*NetRexx *************************************************************
* program to sum the squares of a vector of fifteen numbers.
* program to sum the squares of a vector of fifteen numbers.
* translated from REXX
* translated from REXX
Line 1,824: Line 2,100:
sum=sum + x**2 /*add its square to the sum. */
sum=sum + x**2 /*add its square to the sum. */
end
end
say "The sum of" n "elements for the V vector is:" sum</lang>
say "The sum of" n "elements for the V vector is:" sum</syntaxhighlight>
{{out}}
{{out}}
<pre>The sum of 15 elements for the V vector is: 10650.25</pre>
<pre>The sum of 15 elements for the V vector is: 10650.25</pre>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(apply + (map (fn(x) (* x x)) '(3 1 4 1 5 9)))
<syntaxhighlight lang="newlisp">(apply + (map (fn(x) (* x x)) '(3 1 4 1 5 9)))
-> 133
-> 133
(apply + (map (fn(x) (* x x)) '()))
(apply + (map (fn(x) (* x x)) '()))
-> 0</lang>
-> 0</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import math, sequtils
<syntaxhighlight lang="nim">import math, sequtils


proc sumSquares[T: SomeNumber](a: openArray[T]): T =
echo sum(map(@[1,2,3,4,5], proc (x: int): int = x*x))</lang>
sum(a.mapIt(it * it))

let a1 = [1, 2, 3, 4, 5]
echo a1, " → ", sumSquares(a1)

let a2: seq[float] = @[]
echo a2, " → ", sumSquares(a2)</syntaxhighlight>

{{out}}
<pre>[1, 2, 3, 4, 5] → 55
@[] → 0.0</pre>

=={{header|Oberon-2}}==
{{trans|Modula-3}}
<syntaxhighlight lang="oberon2">
MODULE SumSquares;

IMPORT Out;

VAR
A1:ARRAY 6 OF REAL;

PROCEDURE Init;
BEGIN
A1[0] := 3.0; A1[1] := 1.0; A1[2] := 4.0; A1[3] := 5.0; A1[4] := 9.0;
END Init;
PROCEDURE SumOfSquares(VAR arr:ARRAY OF REAL):REAL;
VAR
i:LONGINT;
sum:REAL;
BEGIN
sum := 0.0;
FOR i := 0 TO LEN(arr)-1 DO
sum := sum + arr[i] * arr[i]
END;
RETURN sum
END SumOfSquares;

BEGIN
Init;
Out.Real(SumOfSquares(A1),0);
Out.Ln
END SumSquares.
</syntaxhighlight>

{{out}}
<pre>1.32E+02
</pre>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class Sum {
class Sum {
Line 1,857: Line 2,182:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>List.fold_left (fun sum a -> sum + a * a) 0 ints</lang>
<syntaxhighlight lang="ocaml">List.fold_left (fun sum a -> sum + a * a) 0 ints</syntaxhighlight>


<lang ocaml>List.fold_left (fun sum a -> sum +. a *. a) 0. floats</lang>
<syntaxhighlight lang="ocaml">List.fold_left (fun sum a -> sum +. a *. a) 0. floats</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==


<lang octave>a = [1:10];
<syntaxhighlight lang="octave">a = [1:10];
sumsq = sum(a .^ 2);</lang>
sumsq = sum(a .^ 2);</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>#sq [1, 1.2, 3, 4.5 ] map sum</lang>
<syntaxhighlight lang="oforth">#sq [1, 1.2, 3, 4.5 ] map sum</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (sum-of-squares l)
(define (sum-of-squares l)
(fold + 0 (map * l l)))
(fold + 0 (map * l l)))
Line 1,881: Line 2,206:
(print (sum-of-squares '(1 2 3 4 5 6 7 8 9 10)))
(print (sum-of-squares '(1 2 3 4 5 6 7 8 9 10)))
; ==> 385
; ==> 385
</syntaxhighlight>
</lang>


=={{header|Order}}==
=={{header|Order}}==


<lang c>#include <order/interpreter.h>
<syntaxhighlight lang="c">#include <order/interpreter.h>


ORDER_PP(8to_lit(
ORDER_PP(8to_lit(
8seq_fold(8plus, 0,
8seq_fold(8plus, 0,
8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(3, 1, 4, 1, 5, 9)))
8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(3, 1, 4, 1, 5, 9)))
))</lang>
))</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {SumOfSquares Xs}
fun {SumOfSquares Xs}
for X in Xs sum:S do
for X in Xs sum:S do
Line 1,900: Line 2,225:
end
end
in
in
{Show {SumOfSquares [3 1 4 1 5 9]}}</lang>
{Show {SumOfSquares [3 1 4 1 5 9]}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
===Generic===
===Generic===
It is possible to apply a function, in this case ^2 to each element of an iterable and sum the result:
It is possible to apply a function, in this case ^2 to each element of an iterable and sum the result:
<lang parigp>ss(v)={
<syntaxhighlight lang="parigp">ss(v)={
sum(i=1,#v,v[i]^2)
sum(i=1,#v,v[i]^2)
};</lang>
};</syntaxhighlight>
===Specific===
===Specific===
For this particular task the product of a row matrix and its transpose is the sum of squares:
For this particular task the product of a row matrix and its transpose is the sum of squares:
<lang parigp>
<syntaxhighlight lang="parigp">
n=[2,5,23]
n=[2,5,23]
print(n*n~)
print(n*n~)
n=[]
n=[]
print(n*n~)
print(n*n~)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,926: Line 2,251:
{{libheader|Math}}
{{libheader|Math}}
Example from the documenation of the run time library:
Example from the documenation of the run time library:
<lang pascal>Program Example45;
<syntaxhighlight lang="pascal">Program Example45;


{ Program to demonstrate the SumOfSquares function. }
{ Program to demonstrate the SumOfSquares function. }
Line 1,944: Line 2,269:
Writeln('Sum squares : ',SumOfSquares(ExArray):8:4);
Writeln('Sum squares : ',SumOfSquares(ExArray):8:4);
Writeln('Sum squares (b) : ',SumOfSquares(@ExArray[1],100):8:4);
Writeln('Sum squares (b) : ',SumOfSquares(@ExArray[1],100):8:4);
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub sum_of_squares {
<syntaxhighlight lang="perl">sub sum_of_squares {
my $sum = 0;
my $sum = 0;
$sum += $_**2 foreach @_;
$sum += $_**2 foreach @_;
Line 1,953: Line 2,278:
}
}


print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang>
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</syntaxhighlight>
or
or
<lang perl>use List::Util qw(reduce);
<syntaxhighlight lang="perl">use List::Util qw(reduce);
sub sum_of_squares {
sub sum_of_squares {
reduce { $a + $b **2 } 0, @_;
reduce { $a + $b **2 } 0, @_;
}
}


print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</lang>
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>?sum(sq_power(tagset(10),2)) -- prints 385</lang>
<span style="color: #008080;">function</span> <span style="color: #000000;">sum_of_squares</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">({{},{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">},</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)},</span><span style="color: #000000;">sum_of_squares</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{0,133,385}
</pre>


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>0 tolist
<syntaxhighlight lang="phixmonti">0 tolist
10 for 0 put endfor
10 for 0 put endfor


Line 1,974: Line 2,306:
endfor
endfor


drop print /# 385 #/</lang>
drop print /# 385 #/</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
function sum_squares(array $args) {
function sum_squares(array $args) {
return array_reduce(
return array_reduce(
Line 1,983: Line 2,315:
);
);
}
}
</syntaxhighlight>
</lang>


In PHP5.3 support for anonymous functions was reworked. While the above code would still work, it is suggested to use
In PHP5.3 support for anonymous functions was reworked. While the above code would still work, it is suggested to use


<lang php>
<syntaxhighlight lang="php">
function sum_squares(array $args) {
function sum_squares(array $args) {
return array_reduce($args, function($x, $y) {
return array_reduce($args, function($x, $y) {
Line 1,993: Line 2,325:
}, 0);
}, 0);
}
}
</syntaxhighlight>
</lang>
Usage for both examples: <code>sum_squares(array(1,2,3,4,5)); // 55</code>
Usage for both examples: <code>sum_squares(array(1,2,3,4,5)); // 55</code>

=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
List = 1..666,
println(sum_squares(List)),
println(sum_squares([])),
nl.

sum_squares([]) = 0.
sum_squares(List) = sum([I*I : I in List]).</syntaxhighlight>

{{out}}
<pre>98691321
0</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>: (sum '((N) (* N N)) (3 1 4 1 5 9))
<syntaxhighlight lang="picolisp">: (sum '((N) (* N N)) (3 1 4 1 5 9))
-> 133
-> 133
: (sum '((N) (* N N)) ())
: (sum '((N) (* N N)) ())
-> 0</lang>
-> 0</syntaxhighlight>

=={{header|PL/0}}==
PL/0 has no arrays but they can be simulated.
<syntaxhighlight lang="pascal">
const maxlist = 5;
var sub, v, l1, l2, l3, l4, l5, sum;
procedure getelement;
begin
if sub = 1 then v := l1;
if sub = 2 then v := l2;
if sub = 3 then v := l3;
if sub = 4 then v := l4;
if sub = 5 then v := l5;
end;
procedure setelement;
begin
if sub = 1 then l1 := v;
if sub = 2 then l2 := v;
if sub = 3 then l3 := v;
if sub = 4 then l4 := v;
if sub = 5 then l5 := v;
end;
procedure sumofsquares;
begin
sub := 0;
sum := 0;
while sub < maxlist do begin
sub := sub + 1;
call getelement;
sum := sum + v * v
end;
end;
begin
sub := 0;
while sub < maxlist do begin
sub := sub + 1;
v := sub;
call setelement;
end;
call sumofsquares;
! sum;
end.
</syntaxhighlight>
{{out}}
<pre>
55
</pre>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);


put (sum(A**2));
put (sum(A**2));
</syntaxhighlight>
</lang>

=={{header|PL/M}}==
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<syntaxhighlight lang="plm">
100H: /* CALCULATE THE SUM OF THE SQUARES OF THE ELEMENTS OF AN ARRAY */

/* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;

/* TASK */

/* RETURNS THE SUM OF THE SQUARES OF THE ARRAY AT A$PTR, UB MUST BE THE */
/* UB MUST BE THE UPPER-BOUND OF THE ARRAY */
SUM$OF$SQUARES: PROCEDURE( A$PTR, UB )ADDRESS;
DECLARE ( A$PTR, UB ) ADDRESS;
DECLARE ( I, SUM ) ADDRESS;
DECLARE A BASED A$PTR ( 0 )ADDRESS;
SUM = 0;
DO I = 0 TO UB;
SUM = SUM + ( A( I ) * A( I ) );
END;
RETURN SUM;
END SUM$OF$SQUARES;

DECLARE VALUES ( 5 )ADDRESS INITIAL( 1, 2, 3, 4, 5 );

CALL PR$NUMBER( SUM$OF$SQUARES( .VALUES, LAST( VALUES ) ) );

EOF
</syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Create a list.
Create a list.
Line 2,043: Line 2,481:
Add the element's ratio times the element's ratio to the ratio.
Add the element's ratio times the element's ratio to the ratio.
Put the element's next into the element.
Put the element's next into the element.
Repeat.</lang>
Repeat.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,051: Line 2,489:
=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>define sum_squares(v);
<syntaxhighlight lang="pop11">define sum_squares(v);
lvars s = 0, j;
lvars s = 0, j;
for j from 1 to length(v) do
for j from 1 to length(v) do
Line 2,059: Line 2,497:
enddefine;
enddefine;


sum_squares({1 2 3 4 5}) =></lang>
sum_squares({1 2 3 4 5}) =></syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang>
<syntaxhighlight lang="text">
/sqrsum{
/sqrsum{
/x exch def
/x exch def
Line 2,077: Line 2,515:
sum ==
sum ==
}def
}def
</syntaxhighlight>
</lang>


{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<syntaxhighlight lang="postscript">
[3 1 4 1 5 9] 0 {dup * +} fold
[3 1 4 1 5 9] 0 {dup * +} fold
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>function Get-SquareSum ($a) {
<syntaxhighlight lang="powershell">function Get-SquareSum ($a) {
if ($a.Length -eq 0) {
if ($a.Length -eq 0) {
return 0
return 0
Line 2,094: Line 2,532:
return $x.Sum
return $x.Sum
}
}
}</lang>
}</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 2,101: Line 2,539:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure SumOfSquares(List base())
<syntaxhighlight lang="purebasic">Procedure SumOfSquares(List base())
ForEach base()
ForEach base()
Sum + base()*base()
Sum + base()*base()
Next
Next
ProcedureReturn Sum
ProcedureReturn Sum
EndProcedure</lang>
EndProcedure</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
'''Using generator expression'''
'''Using generator expression'''
<lang python>sum(x * x for x in [1, 2, 3, 4, 5])
<syntaxhighlight lang="python">sum(x * x for x in [1, 2, 3, 4, 5])
# or
# or
sum(x ** 2 for x in [1, 2, 3, 4, 5])
sum(x ** 2 for x in [1, 2, 3, 4, 5])
# or
# or
sum(pow(x, 2) for x in [1, 2, 3, 4, 5])</lang>
sum(pow(x, 2) for x in [1, 2, 3, 4, 5])</syntaxhighlight>


'''Functional versions:'''
'''Functional versions:'''
<lang python># using lambda and map:
<syntaxhighlight lang="python"># using lambda and map:
sum(map(lambda x: x * x, [1, 2, 3, 4, 5]))
sum(map(lambda x: x * x, [1, 2, 3, 4, 5]))
# or
# or
Line 2,143: Line 2,581:
reduce(add, powers_of_two)
reduce(add, powers_of_two)
# or using a bit more complex lambda
# or using a bit more complex lambda
reduce(lambda a, x: a + x*x, [1, 2, 3, 4, 5])</lang>
reduce(lambda a, x: a + x*x, [1, 2, 3, 4, 5])</syntaxhighlight>


'''Using NumPy:'''
'''Using NumPy:'''
<lang python>import numpy as np
<syntaxhighlight lang="python">import numpy as np
a = np.array([1, 2, 3, 4, 5])
a = np.array([1, 2, 3, 4, 5])
np.sum(a ** 2)</lang>
np.sum(a ** 2)</syntaxhighlight>


=={{header|Q}}==
=={{header|Q}}==
<lang q>ssq:{sum x*x}</lang>
<syntaxhighlight lang="q">ssq:{sum x*x}</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ 0 swap witheach [ 2 ** + ] ] is sumofsquares ( [ --> n )</lang>
<syntaxhighlight lang="quackery"> [ 0 swap witheach [ 2 ** + ] ] is sumofsquares ( [ --> n )</syntaxhighlight>


{{out}}
{{out}}
Line 2,178: Line 2,616:


=={{header|R}}==
=={{header|R}}==
<lang r>arr <- c(1,2,3,4,5)
<syntaxhighlight lang="r">arr <- c(1,2,3,4,5)
result <- sum(arr^2)</lang>
result <- sum(arr^2)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(for/sum ([x #(3 1 4 1 5 9)]) (* x x))
(for/sum ([x #(3 1 4 1 5 9)]) (* x x))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<syntaxhighlight lang="raku" line>say [+] map * ** 2, (3, 1, 4, 1, 5, 9);</syntaxhighlight>
{{works with|Rakudo|#21 "Seattle"}}

<lang perl6>say [+] map * ** 2, 3, 1, 4, 1, 5, 9;</lang>


If this expression seems puzzling, note that <code>* ** 2</code> is equivalent to <code>{$^x ** 2}</code>— the leftmost asterisk is not the multiplication operator but the <code>Whatever</code> star, which specifies currying behavior.
If this expression seems puzzling, note that <code>* ** 2</code> is equivalent to <code>{$^x ** 2}</code>— the leftmost asterisk is not the multiplication operator but the <code>Whatever</code> star, which specifies currying behavior.
Line 2,197: Line 2,633:
as a list infix is looser than comma in precedence but tighter than the reduction list operator:
as a list infix is looser than comma in precedence but tighter than the reduction list operator:


<lang perl6>say [+] 3,1,4,1,5,9 X** 2</lang>
<syntaxhighlight lang="raku" line>say [+] <3 1 4 1 5 9> X** 2</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>define sumOfSqrs use $lst
<syntaxhighlight lang="raven">define sumOfSqrs use $lst
0 $lst each dup * +
0 $lst each dup * +


[ 1 2 3 4] sumOfSqrs "Sum of squares: %d\n" print</lang>
[ 1 2 3 4] sumOfSqrs "Sum of squares: %d\n" print</syntaxhighlight>
{{out}}
{{out}}
<pre>Sum of squares: 30</pre>
<pre>Sum of squares: 30</pre>

=={{header|Red}}==
<syntaxhighlight lang="red">Red [
date: 2021-10-25
red-version: 0.6.4
description: "Find the sum of squares of a numeric vector"
]

sum-squares: function [
"Returns the sum of squares of all values in a block"
values [any-list! vector!]
][
result: 0
foreach value values [result: value * value + result]
result
]

print sum-squares []
print sum-squares [1 2 0.5]</syntaxhighlight>
{{out}}
<pre>
0
5.25
</pre>

=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Prout <SquareSum 1 2 3 4 5>>
};

SquareSum {
= 0;
s.N e.rest = <+ <* s.N s.N> <SquareSum e.rest>>;
};</syntaxhighlight>
{{out}}
<pre>55</pre>

=={{header|ReScript}}==
With integers:
<syntaxhighlight lang="rescript">let sumOfSquares = (acc, item) => { acc + item * item }

Js.log(Js.Array2.reduce([10, 2, 4], sumOfSquares, 0))</syntaxhighlight>

With floats:
<syntaxhighlight lang="rescript">let sumOfSquares = (acc, item) => { acc +. item *. item }

Js.log(Js.Array2.reduce([10., 2., 4.], sumOfSquares, 0.))</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===input from pgm===
===input from pgm===
<lang rexx>/*REXX program sums the squares of the numbers in a (numeric) vector of 15 numbers. */
<syntaxhighlight lang="rexx">/*REXX program sums the squares of the numbers in a (numeric) vector of 15 numbers. */
numeric digits 100 /*allow 100─digit numbers; default is 9*/
numeric digits 100 /*allow 100─digit numbers; default is 9*/
v= -100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with fifteen numbers.*/
v= -100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with fifteen numbers.*/
Line 2,218: Line 2,701:
end /*k*/ /* [↑] if vector is empty, then sum=0.*/
end /*k*/ /* [↑] if vector is empty, then sum=0.*/
/*stick a fork in it, we're all done. */
/*stick a fork in it, we're all done. */
say 'The sum of ' # " squared elements for the V vector is: " $</lang>
say 'The sum of ' # " squared elements for the V vector is: " $</syntaxhighlight>
'''output''' &nbsp; using an internal vector (list) of numbers:
'''output''' &nbsp; using an internal vector (list) of numbers:
<pre>
<pre>
Line 2,225: Line 2,708:


===input from C.L.===
===input from C.L.===
<lang rexx>/*REXX program sums the squares of the numbers in a (numeric) vector of 15 numbers. */
<syntaxhighlight lang="rexx">/*REXX program sums the squares of the numbers in a (numeric) vector of 15 numbers. */
numeric digits 100 /*allow 100─digit numbers; default is 9*/
numeric digits 100 /*allow 100─digit numbers; default is 9*/
parse arg v /*get optional numbers from the C.L. */
parse arg v /*get optional numbers from the C.L. */
Line 2,236: Line 2,719:
end /*until*/ /* [↑] if vector is empty, then sum=0.*/
end /*until*/ /* [↑] if vector is empty, then sum=0.*/
say /*stick a fork in it, we're all done. */
say /*stick a fork in it, we're all done. */
say 'The sum of ' # " squared elements for the V vector is: " $</lang>
say 'The sum of ' # " squared elements for the V vector is: " $</syntaxhighlight>
'''output''' &nbsp; using a vector (list) of numbers from the command line:
'''output''' &nbsp; using a vector (list) of numbers from the command line:
<pre>
<pre>
Line 2,245: Line 2,728:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aList = [1,2,3,4,5]
aList = [1,2,3,4,5]
see sumOfSquares(aList)
see sumOfSquares(aList)
Line 2,255: Line 2,738:
next
next
return sumOfSquares
return sumOfSquares
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|RPL}}==
Zero-length vectors don't exist in RPL, so there's no need to tackle this case:
<lang ruby>[3,1,4,1,5,9].reduce(0){|sum,x| sum + x*x}</lang>
≪ DUP DOT ≫ '<span style="color:blue">∑SQV</span>' STO
If we really need zero-length objects, we can use lists:
≪ 0 SWAP
'''IF''' DUP SIZE '''THEN'''
1 OVER SIZE '''FOR''' j
DUP j GET SQ + '''NEXT'''
'''END''' DROP
≫ '<span style="color:blue">∑SQL</span>' STO
Using RPL 1993:
≪ '''IF''' DUP SIZE '''THEN''' SQ ∑LIST '''ELSE''' SIZE '''END''' ≫ '<span style="color:blue">∑SQL</span>' STO


[ 1 2 3 4 5 ] <span style="color:blue">∑SQV</span>
or with the Ruby 2.4+ method ''sum''.
{ 1 2 3 4 5 } <span style="color:blue">∑SQL</span>
{ } <span style="color:blue">∑SQL</span>
{{out}}
<pre>
3: 55
2: 55
1: 0
</pre>


=={{header|Ruby}}==
<lang ruby>[3,1,4,1,5,9].sum(0){|x| x*x}</lang>
<syntaxhighlight lang="ruby">[3,1,4,1,5,9].sum(0){|x| x*x}</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>list$ = "1,2,3,4,5"
<syntaxhighlight lang="runbasic">list$ = "1,2,3,4,5"
print sumOfSquares(list$)
print sumOfSquares(list$)


Line 2,273: Line 2,775:
sumOfSquares = sumOfSquares + val(word$(sos$,i,","))^2
sumOfSquares = sumOfSquares + val(word$(sos$,i,","))^2
wend
wend
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn sq_sum(v: &[f64]) -> f64 {
<syntaxhighlight lang="rust">fn sq_sum(v: &[f64]) -> f64 {
v.iter().fold(0., |sum, &num| sum + num*num)
v.iter().fold(0., |sum, &num| sum + num*num)
}
}
Line 2,286: Line 2,788:
let u : Vec<f64> = vec![];
let u : Vec<f64> = vec![];
println!("{}", sq_sum(&u));
println!("{}", sq_sum(&u));
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is


sqsum(s, e:FLT):FLT is
sqsum(s, e:FLT):FLT is
Line 2,304: Line 2,806:
end;
end;


end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Unfortunately there is no common "Numeric" class that Int and Double both extend, since Scala's number representation maps closely to Java's. Those concerned about precision can define a similar procedure for integers.
Unfortunately there is no common "Numeric" class that Int and Double both extend, since Scala's number representation maps closely to Java's. Those concerned about precision can define a similar procedure for integers.


<lang scala>def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x}</lang>
<syntaxhighlight lang="scala">def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (sum-of-squares l)
<syntaxhighlight lang="scheme">(define (sum-of-squares l)
(apply + (map * l l)))</lang>
(apply + (map * l l)))</syntaxhighlight>


> (sum-of-squares (list 3 1 4 1 5 9))
> (sum-of-squares (list 3 1 4 1 5 9))
Line 2,319: Line 2,821:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
Line 2,340: Line 2,842:
writeln(squaredSum(list1));
writeln(squaredSum(list1));
writeln(squaredSum(list2));
writeln(squaredSum(list2));
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func sum_of_squares(vector) {
<syntaxhighlight lang="ruby">func sum_of_squares(vector) {
var sum = 0;
var sum = 0;
vector.each { |n| sum += n**2 };
vector.each { |n| sum += n**2 };
Line 2,350: Line 2,852:


say sum_of_squares([]); # 0
say sum_of_squares([]); # 0
say sum_of_squares([1,2,3]); # 14</lang>
say sum_of_squares([1,2,3]); # 14</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>{1. 2. 3} reduce: [|:x :y| y squared + x].
<syntaxhighlight lang="slate">{1. 2. 3} reduce: [|:x :y| y squared + x].
{} reduce: [|:x :y| y squared + x] ifEmpty: [0].</lang>
{} reduce: [|:x :y| y squared + x] ifEmpty: [0].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared]</lang>
<syntaxhighlight lang="smalltalk">#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared]</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 2,366: Line 2,868:
{{works with|CSnobol}}
{{works with|CSnobol}}


<lang SNOBOL4> define('ssq(a)i') :(ssq_end)
<syntaxhighlight lang="snobol4"> define('ssq(a)i') :(ssq_end)
ssq i = i + 1; ssq = ssq + (a<i> * a<i>) :s(sumsq)f(return)
ssq i = i + 1; ssq = ssq + (a<i> * a<i>) :s(sumsq)f(return)
ssq_end
ssq_end
Line 2,374: Line 2,876:
loop i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
loop i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
output = str ' -> ' sumsq(a)
output = str ' -> ' sumsq(a)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,381: Line 2,883:
=={{header|SQL}}==
=={{header|SQL}}==


<lang sql>select sum(x*x) from vector</lang>
<syntaxhighlight lang="sql">select sum(x*x) from vector</syntaxhighlight>


Note that this assumes that the values in our vector are named <code>x</code>.
Note that this assumes that the values in our vector are named <code>x</code>.
Line 2,387: Line 2,889:
=={{header|Standard ML}}==
=={{header|Standard ML}}==


<lang sml>foldl (fn (a, sum) => sum + a * a) 0 ints</lang>
<syntaxhighlight lang="sml">foldl (fn (a, sum) => sum + a * a) 0 ints</syntaxhighlight>


<lang sml>foldl (fn (a, sum) => sum + a * a) 0.0 reals</lang>
<syntaxhighlight lang="sml">foldl (fn (a, sum) => sum + a * a) 0.0 reals</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
=== Mata ===
=== Mata ===
<lang stata>a = 1..100
<syntaxhighlight lang="stata">a = 1..100
sum(a:^2)
sum(a:^2)
338350
338350
Line 2,401: Line 2,903:
0
0
sum(a:^2)
sum(a:^2)
0</lang>
0</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>func sumSq(s: [Int]) -> Int {
<syntaxhighlight lang="swift">func sumSq(s: [Int]) -> Int {
return s.map{$0 * $0}.reduce(0, +)
return s.map{$0 * $0}.reduce(0, +)
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
<lang tcl>proc sumOfSquares {nums} {
templates ssq
set sum 0
when <[](0)> do 0 !
foreach num $nums {
otherwise $... -> $*$ -> ..=Sum&{of: :()} !
set sum [expr {$sum + $num**2}]
end ssq
}
return $sum
}
sumOfSquares {1 2 3 4 5} ;# ==> 55
sumOfSquares {} ;# ==> 0</lang>


[] -> ssq -> !OUT::write // outputs 0
{{tcllib|struct::list}}
[1..5] -> ssq -> !OUT::write // outputs 55
<lang tcl>package require struct::list
</syntaxhighlight>


=={{header|Tcl}}==
proc square x {expr {$x * $x}}
<syntaxhighlight lang="tcl">package require Tcl 8.6
proc + {a b} {expr {$a + $b}}
proc sumOfSquares {nums} {
struct::list fold [struct::list map $nums square] 0 +
}
sumOfSquares {1 2 3 4 5} ;# ==> 55
sumOfSquares {} ;# ==> 0</lang>
Generic "sum of <i>function</i>"
<lang tcl>package require Tcl 8.5
package require struct::list
namespace path ::tcl::mathop
namespace path ::tcl::mathop


# {*} is like apply in Scheme--it turns a list into multiple arguments
proc sum_of {lambda nums} {
proc sum_of_squares lst {
struct::list fold [struct::list map $nums [list apply $lambda]] 0 +
+ {*}[lmap x $lst {* $x $x}]
}
}
puts [sum_of_squares {1 2 3 4}]; # ==> 30

sum_of {x {* $x $x}} {1 2 3 4 5} ;# ==> 55</lang>
puts [sum_of_squares {}]; # ==> 0
</syntaxhighlight>


=={{header|Trith}}==
=={{header|Trith}}==
<lang trith>[3 1 4 1 5 9] 0 [dup * +] foldl</lang>
<syntaxhighlight lang="trith">[3 1 4 1 5 9] 0 [dup * +] foldl</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
array="3'1'4'1'5'9",sum=0
array="3'1'4'1'5'9",sum=0
Line 2,452: Line 2,945:
ENDLOOP
ENDLOOP
PRINT sum
PRINT sum
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,460: Line 2,953:
=={{header|UnixPipes}}==
=={{header|UnixPipes}}==


<lang bash>folder() {
<syntaxhighlight lang="bash">folder() {
(read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res)
(read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res)
}
}
Line 2,471: Line 2,964:




(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold</lang>
(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold</syntaxhighlight>


=={{header|Unix shell}}==
=={{header|UNIX Shell}}==
<syntaxhighlight lang="sh">sum_squares () {
<lang Unixshell>cat toto
_r=0
1
for _n
2
do
4
: "$((_r += _n * _n))"
8
done
16
echo "$_r"
cat toto toto | paste -sd*
}
1*2*4*8*16*1*2*4*8*16

cat toto toto | paste -sd* | bc -l
sum_squares 3 1 4 1 5 9</syntaxhighlight>
1048576
</lang>
<lang shell>cat titi
0
cat titi titi | paste -sd* | bc -l
0
</lang>
{{out}}
{{out}}
<pre>
<pre>133</pre>
with the limits of what can compute bc of course.
</pre>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 2,500: Line 2,985:
maps the product function to all pairs, and then sums the
maps the product function to all pairs, and then sums the
result by way of the reduction operator, -:.
result by way of the reduction operator, -:.
<lang Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat


ssq = sum:-0+ product*iip
ssq = sum:-0+ product*iip
Line 2,506: Line 2,991:
#cast %n
#cast %n


main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93></lang>
main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93></syntaxhighlight>
{{out}}
{{out}}
<pre>62223</pre>
<pre>62223</pre>


=={{header|V}}==
=={{header|V}}==
<lang v>[sumsq [dup *] map 0 [+] fold].
<syntaxhighlight lang="v">[sumsq [dup *] map 0 [+] fold].


[] sumsq
[] sumsq
=0
=0
[1 2 3] sumsq</lang>
[1 2 3] sumsq</syntaxhighlight>
=14
=14


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub sum_of_squares()
<syntaxhighlight lang="vb">Public Sub sum_of_squares()
Debug.Print WorksheetFunction.SumSq([{1,2,3,4,5,6,7,8,9,10}])
Debug.Print WorksheetFunction.SumSq([{1,2,3,4,5,6,7,8,9,10}])
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 385 </pre>
<pre> 385 </pre>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function sum_of_squares(arr)
Function sum_of_squares(arr)
If UBound(arr) = -1 Then
If UBound(arr) = -1 Then
Line 2,537: Line 3,022:
WScript.StdOut.WriteLine sum_of_squares(Array(1,2,3,4,5))
WScript.StdOut.WriteLine sum_of_squares(Array(1,2,3,4,5))
WScript.StdOut.WriteLine sum_of_squares(Array())
WScript.StdOut.WriteLine sum_of_squares(Array())
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,546: Line 3,031:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>
<syntaxhighlight lang="vbnet">
Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer
Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer
If i Is Nothing OrElse i.Count = 0 Then
If i Is Nothing OrElse i.Count = 0 Then
Line 2,583: Line 3,068:
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,604: Line 3,089:
SumOfSquares(15) = 1240
SumOfSquares(15) = 1240
SumOfSquares(16) = 1496
SumOfSquares(16) = 1496
</pre>

=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">
1000 :1)=1
1010 :2)=2
1020 :3)=3
1030 :4)=4
1040 :5)=5
1050 L=5
1060 #=2000
1070 ?=S
1080 #=9999
2000 R=!
2010 S=0
2020 I=1
2030 #=I<L+(I=L)=0*R
2040 S=I*I+S
2050 I=I+1
2060 #=2030
</syntaxhighlight>
{{out}}
<pre>
55
</pre>
</pre>


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@sum !*^@sq [3 1 4 1 5 9] ; returns 133</lang>
<syntaxhighlight lang="wortel">@sum !*^@sq [3 1 4 1 5 9] ; returns 133</syntaxhighlight>
<lang wortel>@sum !*^@sq [] ; returns 0</lang>
<syntaxhighlight lang="wortel">@sum !*^@sq [] ; returns 0</syntaxhighlight>
As a function:
As a function:
<lang wortel>^(@sum *^@sq)</lang>
<syntaxhighlight lang="wortel">^(@sum *^@sq)</syntaxhighlight>
Iterative function:
Iterative function:
<lang wortel>&a [@var sum 0 @for x of a :!+sum *x x sum]</lang>
<syntaxhighlight lang="wortel">&a [@var sum 0 @for x of a :!+sum *x x sum]</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var sumSquares = Fn.new { |v| v.reduce(0) { |sum, n| sum + n * n } }
<syntaxhighlight lang="wren">var sumSquares = Fn.new { |v| v.reduce(0) { |sum, n| sum + n * n } }


var v = [1, 2, 3, -1, -2, -3]
var v = [1, 2, 3, -1, -2, -3]
System.print("Vector : %(v)")
System.print("Vector : %(v)")
System.print("Sum of squares : %(sumSquares.call(v))")</lang>
System.print("Sum of squares : %(sumSquares.call(v))")</syntaxhighlight>


{{out}}
{{out}}
Line 2,629: Line 3,138:
=={{header|XLISP}}==
=={{header|XLISP}}==
The task specification calls for a function that takes a numeric vector. If you want a function that takes a linked list (which would be more idiomatic), just extract the inner function <tt>SUMSQ</tt> and use that instead of <tt>SUM-OF-SQUARES</tt>.
The task specification calls for a function that takes a numeric vector. If you want a function that takes a linked list (which would be more idiomatic), just extract the inner function <tt>SUMSQ</tt> and use that instead of <tt>SUM-OF-SQUARES</tt>.
<lang lisp>(defun sum-of-squares (vec)
<syntaxhighlight lang="lisp">(defun sum-of-squares (vec)
(defun sumsq (xs)
(defun sumsq (xs)
(if (null xs)
(if (null xs)
Line 2,642: Line 3,151:
(print `(the sum of the squares of the first seven prime numbers is ,(sum-of-squares first-seven-primes)))
(print `(the sum of the squares of the first seven prime numbers is ,(sum-of-squares first-seven-primes)))


(print `(the sum of the squares of no numbers at all is ,(sum-of-squares zero-length-vector)))</lang>
(print `(the sum of the squares of no numbers at all is ,(sum-of-squares zero-length-vector)))</syntaxhighlight>
{{out}}
{{out}}
<pre>(THE SUM OF THE SQUARES OF THE FIRST SEVEN PRIME NUMBERS IS 666)
<pre>(THE SUM OF THE SQUARES OF THE FIRST SEVEN PRIME NUMBERS IS 666)
Line 2,648: Line 3,157:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


func SumSq(V, L);
func SumSq(V, L);
Line 2,660: Line 3,169:
[IntOut(0, SumSq([1,2,3,4,5,6,7,8,9,10], 10)); CrLf(0);
[IntOut(0, SumSq([1,2,3,4,5,6,7,8,9,10], 10)); CrLf(0);
IntOut(0, SumSq([0], 0)); CrLf(0); \zero-length vector "[]" doesn't compile
IntOut(0, SumSq([0], 0)); CrLf(0); \zero-length vector "[]" doesn't compile
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,669: Line 3,178:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>T().reduce(fcn(p,n){ p + n*n },0) //-->0
<syntaxhighlight lang="zkl">T().reduce(fcn(p,n){ p + n*n },0) //-->0
T(3,1,4,1,5,9).reduce(fcn(p,n){ p + n*n },0.0) //-->133.0
T(3,1,4,1,5,9).reduce(fcn(p,n){ p + n*n },0.0) //-->133.0
[1..5].reduce(fcn(p,n){ p + n*n },0) //-->55</lang>
[1..5].reduce(fcn(p,n){ p + n*n },0) //-->55</syntaxhighlight>

Latest revision as of 10:38, 11 February 2024

Task
Sum of squares
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Write a program to find the sum of squares of a numeric vector.

The program should work on a zero-length vector (with an answer of   0).


Related task



0815

{x{*%<:d:~$<:1:~>><:2:~>><:3:~>><:4:~>><:5:~>><:6:~>><:7:
~>><:8:~>><:9:~>><:a:~>><:b:~>><:c:~>><:ffffffffffffffff:
~>{x{*>}:8f:{x{*&{=+>{~>&=x<:ffffffffffffffff:/#:8f:{{~%
Output:
0
28A

11l

print(sum([1, 2, 3, 4, 5].map(x -> x^2)))
Output:
55

360 Assembly

*        Sum of squares            27/08/2015
SUMOFSQR CSECT
         USING  SUMOFSQR,R12
         LR     R12,R15
         LA     R7,A               a(1)
         SR     R6,R6              sum=0
         LA     R3,1               i=1
LOOPI    CH     R3,N               do i=1 to hbound(a)
         BH     ELOOPI
         L      R5,0(R7)           a(i)
         M      R4,0(R7)           a(i)*a(i)
         AR     R6,R5              sum=sum+a(i)**2
         LA     R7,4(R7)           next a
         LA     R3,1(R3)           i=i+1
         B      LOOPI              end i
ELOOPI   XDECO  R6,PG+23           edit sum
         XPRNT  PG,80
         XR     R15,R15
         BR     R14
A        DC     F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
PG       DC     CL80'The sum of squares is: '
N        DC     AL2((PG-A)/4)
         YREGS
         END    SUMOFSQR
Output:
The sum of squares is:          385

8086 Assembly

		;;; Sum of squares
		cpu	8086
		bits	16
section		.text
		org	100h
		jmp	demo
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;;; Calculate the sum of the squares of the array in SI.
		;;; The array should contain 16-bit unsigned integers.
		;;; The output will be 32-bit.
		;;; Input: (DS:)SI = array, CX = array length
		;;; Output: DX:AX = sum of squares
		;;; Registers used: AX,BX,CX,DX,SI,DI
sumsqr:		xor	bx,bx	; Keep accumulator in BX:DI.
		xor	di,di	; (So zero it out first)
		and	cx,cx	; Counter register 0? "Program should work
		jz	.done	; on a zero-length vector"
.loop:		mov	ax,[si]	; Grab value from array
		mul	ax	; Calculate square of value (into DX:AX)
		add	di,ax	; Add low 16 bits to accumulator
		adc	bx,dx	; Add high 16 bits, plus carry
		inc	si	; Point to next value
		inc	si
		loop	.loop	; Next value in array
.done:		mov	ax,di	; Return the value in DX:AX as is tradition
		mov	dx,bx
		ret
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;;; Demo: use the subroutine to calculate the sum of squares
		;;; in the included array, and show the result
demo:		mov	si,array
		mov	cx,arrlen
		call	sumsqr
		;;; Print the return value in DX:AX as a decimal number
		;;; (Note: max supported value 655359 - this is a limitation
		;;; of this rudimentary output code, not of the sum of squares
		;;; routine.)
		mov	di,outstr_end
		mov	cx,10
.decloop:	div	cx
		dec	di
		add	dl,'0'
		mov	[di],dl
		xor	dx,dx
		and	ax,ax
		jnz	.decloop
		mov	dx,di
		mov	ah,9
		int	21h
		ret
section		.data
outstr:		db	'######'	; Placeholder for decimal output 
outstr_end:	db	'$'
array:		dw	1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
arrlen:		equ	($-array)/2	; length is in words

ACL2

(defun sum-of-squares (xs)
   (if (endp xs)
       0
       (+ (* (first xs) (first xs))
          (sum-of-squares (rest xs)))))

Action!

CARD FUNC SumOfSqr(BYTE ARRAY a BYTE count)
  BYTE i
  CARD res

  IF count=0 THEN
    RETURN (0)
  FI

  res=0
  FOR i=0 TO count-1
  DO
    res==+a(i)*a(i)
  OD
RETURN (res)

PROC Test(BYTE ARRAY a BYTE count)
  BYTE i
  CARD res

  res=SumOfSqr(a,count)
  Print("[")
  IF count>0 THEN
    FOR i=0 to count-1
    DO
      PrintB(a(i))
      IF i<count-1 THEN
        Put(' )
      FI
    OD
  FI
  PrintF("]->%U%E%E",res)
RETURN

PROC Main()
  BYTE ARRAY a=[1 2 3 4 5]
  BYTE ARRAY b=[10 20 30 40 50 60 70 80 90]
  BYTE ARRAY c=[11]
  
  Test(a,5)
  Test(b,9)
  Test(c,1)
  Test(c,0)
RETURN
Output:

Screenshot from Atari 8-bit computer

[1 2 3 4 5]->55

[10 20 30 40 50 60 70 80 90]->28500

[11]->121

[]->0

ActionScript

function sumOfSquares(vector:Vector.<Number>):Number
{
	var sum:Number = 0;
	for(var i:uint = 0; i < vector.length; i++)
		sum += vector[i]*vector[i];
	return sum;
}

Ada

with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Sum_Of_Squares is
   type Float_Array is array (Integer range <>) of Float;

   function Sum_Of_Squares (X : Float_Array) return Float is
      Sum : Float := 0.0;
   begin
      for I in X'Range loop
         Sum := Sum + X (I) ** 2;
      end loop;
      return Sum;
   end Sum_Of_Squares;
   
begin
   Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array
   Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0))));
end Test_Sum_Of_Squares;
Output:
 0.00000E+00
 1.33000E+02

Aime

real
squaredsum(list l)
{
    integer i;
    real s;

    s = 0;
    i = -~l;
    while (i) {
        s += sq(l[i += 1]);
    }

    s;
}

integer
main(void)
{
    list l;

    l = list(0, 1, 2, 3);

    o_form("~\n", squaredsum(l));
    o_form("~\n", squaredsum(list()));
    o_form("~\n", squaredsum(list(.5, -.5, 2)));

    0;
}
Output:
14
0
4.5

ALGOL 60

Works with: GNU Marst version Any - tested with release 2.7

Using Jensen's Device.

begin
   integer i;
   integer array A[ 1 : 5 ];
   real procedure sum (i, lo, hi, term);
      value lo, hi;
      integer i, lo, hi;
      real term;
      comment term is passed by-name, and so is i;
   begin
      real temp;
      temp := 0;
      for i := lo step 1 until hi do
         temp := temp + term;
      sum := temp
   end;
   comment initialie A;
   for i := 1 step 1 until 5 do A[i] := i;
   comment note the correspondence between the mathematical notation and the call to sum;
   outreal(1, sum (i, 1, 5, A[i] * A[i]))
end

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

The computation can be written as a loop.

PROC sum of squares = ([]REAL argv)REAL:(
  REAL sum := 0;
  FOR i FROM LWB argv TO UPB argv DO
    sum +:= argv[i]**2
  OD;
  sum
);
test:(
  printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));
)
Output:
133

Another implementation could define a procedure (proc) or operator (op) called map.

Translation of: python
[]REAL data = (3, 1, 4, 1, 5, 9);

PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL:
    ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out);

test:(
  REAL sum := 0;
  printf(($xg(0)l$, map ( ((REAL argv)REAL: sum +:= argv ** 2), data) ));

  PRIO MAP = 5; # the same priority as the operators <, =<, >=, & > maybe... #
  OP MAP = ( PROC(REAL)REAL func, []REAL argv)REAL:
    ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out);

  sum := 0;
  printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data ))
)
Output:
133
133
Works with: ALGOL 68 version Revision 1 - requires the Currying extension
Works with: ALGOL 68G version Any - tested with release a68g-2.8.3


The computation can be written as a generator.

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

MODE YIELDREAL = PROC(REAL)VOID;
MODE GENREAL = PROC(YIELDREAL)VOID;

PROC gen real of vector = ([]REAL data, YIELDREAL yield)VOID:
  FOR i FROM LWB data TO UPB data DO yield(data[i]) OD;

PROC real sum sq of gen = (GENREAL gen real)REAL: (
  REAL sum:=0;
# FOR REAL value IN # gen real(#) DO (#
     (REAL value)VOID:(
       sum+:=value**2
# OD #));
  sum
);

PROC real sum map of gen = (PROC(REAL)REAL func, GENREAL gen real)REAL: (
  REAL sum:=0;
# FOR REAL value IN # gen real(#) DO (#
     (REAL value)VOID:(
       sum+:=func(value)
# OD #));
  sum
);

OP GEN = ([]REAL array)GENREAL:gen real of vector(array,);

OP (GENREAL #gen real#)REAL SUMSQ = real sum sq of gen;

PRIO SUMMAP = 5;
OP (PROC(REAL)REAL #func#, GENREAL #gen real#)REAL SUMMAP = real sum map of gen;

test:(
  []REAL data = (3, 1, 4, 1, 5, 9);
# Permutations of the above routines #
  printf(($"real sum sq GEN: "g(0)l$, real sum sq of gen(GEN data)));
  printf(($"real sum sq real gen: "g(0)l$, real sum sq of gen(gen real of vector(data,))));
  printf(($"real sum map real gen: "g(0)l$, real sum map of gen(((REAL x)REAL: x*x),gen real of vector(data,))));
  printf(($"SUMSQ real gen: "g(0)l$, SUMSQ gen real of vector(data,)));
  printf(($"SUMSQ GEN: "g(0)l$, SUMSQ GEN data));
  printf(($"sq SUMMAP GEN: "g(0)l$, ((REAL x)REAL: x*x)SUMMAP GEN data))
)
Output:
real sum sq GEN: 133
real sum sq real gen: 133
real sum map real gen: 133
SUMSQ real gen: 133
SUMSQ GEN: 133
sq SUMMAP GEN: 133

ALGOL W

Using a dedicated "sum of squares" procedure

begin
    % procedure to sum the squares of the elements of a vector.              %
    % the bounds of the vector must be passed in lb and ub                   %
    real procedure sumSquares ( real    array vector ( * )
                              ; integer value lb
                              ; integer value ub
                              ) ;
    begin
        real sum;
        sum := 0;
        for i := lb until ub do sum := sum + ( vector( i ) * vector( i ) );
        sum
    end sumOfSquares ;

    % test the sumSquares procedure                                          %
    real array numbers ( 1 :: 5 );
    for i := 1 until 5 do numbers( i ) := i;
    r_format := "A"; r_w := 10; r_d := 1; % set fixed point output           %
    write( sumSquares( numbers, 1, 5 ) );
end.

Using Jensen's device

Translation of: ALGOL60

Using the classic Jensen's Device (first introduced in Algol 60) we can use a generic summation procedure, as in this sample:

begin % sum the squares of the elements of a vector, using Jensen's Device %
   integer i;
   real procedure sum  ( integer %name% i; integer value lo, hi; real procedure term );
      % i is passed by-name, term is passed as a procedure which makes it effectively passed by-name %
   begin
       real temp;
       temp := 0;
       i := lo;
       while i <= hi do begin      % The Algol W "for" loop (as in Algol 68) creates a distinct %
           temp := temp + term;    % variable which would not be shared with the passed "i" %
           i := i + 1              % Here the actual passed "i" is incremented. %
       end while_i_le_temp;
       temp
   end;
   real array A ( 1 :: 5 );
   for i := 1 until 5 do A( i ) := i;
   r_format := "A"; r_w := 10; r_d := 1; % set fixed point output %
   write( sum( i, 1, 5, A( i ) * A( i ) ) );
end.

Alore

def sum_squares(a)
   var sum = 0
   for i in a
      sum = sum + i**2
   end
   return sum
end

WriteLn(sum_squares([3,1,4,1,5,9]))
end

APL

      square_sum{+/*2}
      square_sum 1 2 3 4 5
55
      square_sum  ⍝The empty vector
0

AppleScript

Two ways of composing a sumOfSquares function:

------ TWO APPROACHES – SUM OVER MAP, AND DIRECT FOLD ----

-- sumOfSquares :: Num a => [a] -> a
on sumOfSquares(xs)
    script squared
        on |λ|(x)
            x ^ 2
        end |λ|
    end script
    
    sum(map(squared, xs))
end sumOfSquares


-- sumOfSquares2 :: Num a => [a] -> a
on sumOfSquares2(xs)
    script plusSquare
        on |λ|(a, x)
            a + x ^ 2
        end |λ|
    end script
    
    foldl(plusSquare, 0, xs)
end sumOfSquares2


--------------------------- TEST -------------------------
on run
    set xs to [3, 1, 4, 1, 5, 9]
    
    {sumOfSquares(xs), sumOfSquares2(xs)}
    
    -- {133.0, 133.0}
end run


-------------------- GENERIC FUNCTIONS -------------------

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl


-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map


-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


-- sum :: Num a => [a] -> a
on sum(xs)
    script add
        on |λ|(a, b)
            a + b
        end |λ|
    end script
    
    foldl(add, 0, xs)
end sum
Output:
{133.0, 133.0}

Arturo

arr: 1..10

print sum map arr [x][x^2]
Output:
385

Astro

sum([1, 2, 3, 4]²)

Asymptote

int suma;
int[] a={1, 2, 3, 4, 5, 6};
  
for(var i : a)
    suma = suma + a[i] ^ 2;

write("The sum of squares is: ", suma);

AutoHotkey

list = 3 1 4 1 5 9
Loop, Parse, list, %A_Space%
 sum += A_LoopField**2
MsgBox,% sum

AWK

Vectors are read, space-separated, from stdin; sum of squares goes to stdout. The empty line produces 0.

$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}'
3 1 4 1 5 9
133

0

BASIC

Works with: QBasic

Assume the numbers are in an array called a.

sum = 0
FOR I = LBOUND(a) TO UBOUND(a)
  sum = sum + a(I) ^ 2
NEXT I
PRINT "The sum of squares is: " + sum

BaCon

' Sum of squares
FUNCTION ss(int arr[], NUMBER elem)
    sum = 0
    FOR i = 0 TO elem - 1
        sum = sum + POW(arr[i], 2)
    NEXT
    RETURN sum
END FUNCTION

' 1 to 10 in the test vector, or 1 to -s n
option = CMDLINE("s:")
IF option = ASC("s") THEN
    elem = VAL(ARGUMENT$)
ELSE
    elem = 10
END IF

DECLARE vector TYPE int ARRAY elem
FOR i = 0 TO elem - 1
    vector[i] = i + 1
NEXT
PRINT ss(vector, elem)
Output:
prompt$ ./sumsquares
385
prompt$ ./sumsquares -s 1000
333833500

BASIC256

arraybase 1

dim a(6)
a[1] = 1.0
a[2] = 2.0
a[3] = 3.0
a[4] = -1.0
a[5] = -2.0
a[6] = -3.0

sum = 0
for i = 1 to a[?]
	sum += a[i] ^ 2
next i
print "The sum of squares is: "; sum
end

BBC BASIC

BBC BASIC cannot have a zero-length array.

      DIM vector(5)
      vector() = 1, 2, 3, 4, 5, 6
      
      PRINT "Sum of squares = " ; MOD(vector()) ^ 2
Output:
Sum of squares = 91

IS-BASIC

100 INPUT PROMPT "Number of elements: ":N
110 NUMERIC A(1 TO N)
120 FOR I=1 TO N
130   PRINT I;:INPUT PROMPT ". = ":A(I)
140 NEXT
150 PRINT "The sum of squares is:";SQ(A)
160 DEF SQ(REF T)
170   LET S=0
180   FOR I=LBOUND(T) TO UBOUND(T)
190     LET S=S+T(I)^2
200   NEXT
210   LET SQ=S
220 END DEF

Yabasic

data 1.0, 2.0, 3.0, -1.0, -2.0, -3.0
dim a(5)
sum = 0

for i = 0 to arraysize(a(), 1)
    read a(i)
    sum = sum + a(i) ^ 2
next i
print "The sum of squares is: ", sum
end

bc

define s(a[], n) {
    auto i, s
    
    for (i = 0; i < n; i++) {
        s += a[i] * a[i]
    }
    
    return(s)
}

BCPL

get "libhdr"

let sumsquares(v, len) =
    len=0 -> 0,
    !v * !v + sumsquares(v+1, len-1)
    
let start() be
$(  let vector = table 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    writef("%N*N", sumsquares(vector, 10))
$)
Output:
385

BQN

Similar to the BQN entry in Sum of a series.

SSq  +´

•Show SSq 12345
•Show SSq ⟨⟩
55
0

Bracmat

( ( sumOfSquares
  =   sum component
    .   0:?sum
      &   whl
        ' ( !arg:%?component ?arg
          & !component^2+!sum:?sum
          )
      & !sum
  )
& out$(sumOfSquares$(3 4))
& out$(sumOfSquares$(3 4 i*5))
& out$(sumOfSquares$(a b c))
);
Output:
25
0
a^2+b^2+c^2

Brat

p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 }  #Prints 385

C

#include <stdio.h>

double squaredsum(double *l, int e)
{
   int i; double sum = 0.0;
   for(i = 0 ; i < e ; i++) sum += l[i]*l[i];
   return sum;
}

int main()
{
   double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0};
   
   printf("%lf\n", squaredsum(list, 6));
   printf("%lf\n", squaredsum(list, 0));
   /* the same without using a real list as if it were 0-element long */
   printf("%lf\n", squaredsum(NULL, 0));
   return 0;
}

C#

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static int SumOfSquares(IEnumerable<int> list)
    {
        return list.Sum(x => x * x);
    }
    static void Main(string[] args)
    {
        Console.WriteLine(SumOfSquares(new int[] { 4, 8, 15, 16, 23, 42 })); // 2854
        Console.WriteLine(SumOfSquares(new int[] { 1, 2, 3, 4, 5 })); // 55
        Console.WriteLine(SumOfSquares(new int[] { })); // 0
    }
}

C++

Using accumulate

#include <iostream>
#include <numeric>
#include <vector>

double add_square(double prev_sum, double new_val)
{
  return prev_sum + new_val*new_val;
}

double vec_add_squares(std::vector<double>& v)
{
  return std::accumulate(v.begin(), v.end(), 0.0, add_square);
}

int main()
{
  // first, show that for empty vectors we indeed get 0
  std::vector<double> v; // empty
  std::cout << vec_add_squares(v) << std::endl;

  // now, use some values
  double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 };
  v.assign(data, data+7);
  std::cout << vec_add_squares(v) << std::endl;
  return 0;
}

Using inner_product

#include <iostream>
#include <numeric>
#include <vector>

int main()
{
  // first, show that for empty vectors we indeed get 0
  std::vector<double> v; // empty
  std::cout << std::inner_product(begin(v), end(v), begin(v), 0.0) << std::endl;
  
  // now, use some values
  double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 };
  v.assign(data, data+7);
  std::cout << std::inner_product(begin(v), end(v), begin(v), 0.0) << std::endl;
  return 0;
}

Using Boost.Lambda

Library: Boost.Lambda
#include <numeric>
#include <vector>
#include "boost/lambda/lambda.hpp"

double vec_add_squares(std::vector<double>& v)
{
  using namespace boost::lambda;

  return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2);
}

Chef

Sum of squares.

First input is length of vector, then rest of input is vector.

Ingredients.
1 g eggs
0 g bacon

Method.
Put bacon into the 1st mixing bowl.
Take eggs from refrigerator.
Square the eggs.
Take bacon from refrigerator.
Put bacon into 2nd mixing bowl.
Combine bacon into 2nd mixing bowl.
Fold bacon into 2nd mixing bowl.
Add the bacon into the 1st mixing bowl.
Ask the eggs until squared.
Pour contents of the 1st mixing bowl into the 1st baking dish.

Serves 1.

Clojure

(defn sum-of-squares [v]
  (reduce #(+ %1 (* %2 %2)) 0 v))

CLU

sum_squares = proc (ns: sequence[int]) returns (int)
    sum: int := 0
    for n: int in sequence[int]$elements(ns) do
        sum := sum + n ** 2
    end
    return(sum)
end sum_squares

start_up = proc ()
    po: stream := stream$primary_output()
    
    stream$putl(po, int$unparse(sum_squares(sequence[int]$[])))
    stream$putl(po, int$unparse(sum_squares(sequence[int]$[1,2,3,4,5])))
    stream$putl(po, int$unparse(sum_squares(sequence[int]$[42])))
end start_up
Output:
0
55
1764

CoffeeScript

sumOfSquares = ( list ) ->
    list.reduce (( sum, x ) -> sum + ( x * x )), 0

Common Lisp

(defun sum-of-squares (vector)
  (loop for x across vector sum (expt x 2)))

Or in a functional way:

(defun sum-of-squares (vec)
  (reduce #'+ (map 'vector (lambda (x) (* x x)) vec)))

Cowgol

include "cowgol.coh";
include "argv.coh";

# Sum of squares
sub sumsquare(vec: [int32], len: intptr): (out: uint32) is  
    out := 0;    
    while len > 0 loop
        var cur := [vec];
        # make positive first so we can use extra range of uint32
        if cur < 0 then cur := -cur; end if;
        out := out + cur as uint32 * cur as uint32;
        vec := @next vec;
        len := len - 1;
    end loop;
end sub;


# Read array from command line, allowing empty line (giving 0)
var nums: int32[128];
var len: @indexof nums := 0;

ArgvInit();
loop
    var argmt := ArgvNext(); # read number
    if argmt == (0 as [uint8]) then
        break; # stop when no more numbers
    end if;
    
    var dummy: [uint8];
    (nums[len], dummy) := AToI(argmt);
    len := len + 1;
end loop;

# Print sum of squares of numbers
print_i32(sumsquare(&nums[0], len as intptr));
print_nl();
Output:
$ ./sumsq.386
0
$ ./sumsq.386 {1..30}
9455
$ ./sumsq.386 512
262144

Crystal

def sum_squares(a)
    a.map{|e| e*e}.sum()
end

puts sum_squares([1, 2, 3])
# => 14

D

Iterative Version

T sumSquares(T)(T[] a) pure nothrow @safe @nogc {
    T sum = 0;
    foreach (e; a)
        sum += e ^^ 2;
    return sum;
}

void main() {
    import std.stdio: writeln;

    [3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln;
}
Output:
133.61

Polymorphic Functional Style

import std.stdio, std.algorithm, std.traits, std.range;

auto sumSquares(Range)(Range data) pure nothrow @safe @nogc {
    return reduce!q{a + b ^^ 2}(ForeachType!Range(0), data);
}

void main() {
    immutable items = [3.1, 1.0, 4.0, 1.0, 5.0, 9.0];
    items.sumSquares.writeln;
    10.iota.sumSquares.writeln;
}
Output:
133.61
285

Dart

Iterative Version

sumOfSquares(list) {
  var sum=0;
  list.forEach((var n) { sum+=(n*n); });
  return sum;
}
 
main() {
  print(sumOfSquares([]));
  print(sumOfSquares([1,2,3]));
  print(sumOfSquares([10]));
}
Output:
0
14
100

Functional Style Version

num sumOfSquares(List<num> l) => l.map((num x)=>x*x)
				  .fold(0, (num p,num n)=> p + n);

void main(){
  print(sumOfSquares([]));
  print(sumOfSquares([1,2,3]));
  print(sumOfSquares([10]));
}
Output:
0
14
100

Delphi

Delphi has standard SumOfSquares function in Math unit:

program SumOfSq;

{$APPTYPE CONSOLE}

uses Math;

type
  TDblArray = array of Double;

var
  A: TDblArray;

begin
  Writeln(SumOfSquares([]):6:2);            //  0.00
  Writeln(SumOfSquares([1, 2, 3, 4]):6:2);  // 30.00
  A:= nil;
  Writeln(SumOfSquares(A):6:2);             //  0.00
  A:= TDblArray.Create(1, 2, 3, 4);
  Writeln(SumOfSquares(A):6:2);             // 30.00
  Readln;
end.

Draco

proc nonrec sum_squares([*] int arr) ulong:
    ulong sum, item;
    word i, len;
    sum := 0;
    len := dim(arr,1);
    if len>0 then
        for i from 0 upto len-1 do 
            item := |arr[i];
            sum := sum + item * item
        od
    fi;
    sum
corp

proc nonrec main() void:
    type A0 = [0] int, 
         A1 = [1] int, 
         A5 = [5] int;
    
    writeln(sum_squares(A0()));
    writeln(sum_squares(A1(42)));
    writeln(sum_squares(A5(1,2,3,4,5)))
corp
Output:
0
1764
55

E

def sumOfSquares(numbers) {
    var sum := 0
    for x in numbers {
        sum += x**2
    }
    return sum
}

EasyLang

nums[] = [ 1 2 3 4 5 ]
for v in nums[]
   sum += v * v
.
print sum

Eiffel

class
	APPLICATION

create
	make

feature -- Initialization

	make
		local
			a: ARRAY [INTEGER]
		do
			a := <<1, -2, 3>>
			print ("%NSquare sum of <<1, 2, 3>>: " + sum_of_square (a).out)

			a := <<>>
			print ("%NSquare sum of <<>>: " + sum_of_square (a).out)
		end

feature -- Access

	sum_of_square (a: ITERABLE [INTEGER]): NATURAL
			-- sum of square of each items
		do
			Result := 0
			across a as it loop
				Result := Result + (it.item * it.item).as_natural_32
			end
		end

end

Elena

ELENA 6.x :

import system'routines;
import extensions;
 
SumOfSquares(list)
    = list.selectBy::(x => x * x).summarize(new Integer());
 
public program()
{
    console 
        .printLine(SumOfSquares(new int[]{4, 8, 15, 16, 23, 42}))
        .printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5}))
        .printLine(SumOfSquares(Array.MinValue))
}
Output:
2854
55
0

Elixir

iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end)
133

Emacs Lisp

(defun sum-of-squares (numbers)
  (apply #'+ (mapcar (lambda (k) (* k k)) numbers)))

(sum-of-squares (number-sequence 0 3)) ;=> 14

Erlang

lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).

Euler

Using Jensen's Device

begin
   new i; new A; new sum;
   sum <- ` formal i; formal lo; formal hi; formal term;
            begin
                new temp; label loop;
                temp <- 0;
                i    <- lo;
loop:           begin
                    temp <- temp + term;
                    if [ i <- i + 1 ] <= hi then goto loop else 0
                end;
                temp
            end
          ';

   A <- ( 1, 2, 3, 4, 5 );
   out sum( @i, 1, length A, `A[i]*A[i]' )
end $

Euphoria

function SumOfSquares(sequence v)
    atom sum
    sum = 0
    for i = 1 to length(v) do
        sum += v[i]*v[i]
    end for
    return sum
end function

Excel

To find the sum of squares of values from A1 to A10, type in any other cell :

=SUMSQ(A1:A10)

The above expression will return zero if there are no values in any cell.

12	3	5	23	13	67	15	9	4	2
									
5691

F#

[1 .. 10] |> List.fold (fun a x -> a + x * x) 0 
[|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 0

Factor

USE: math sequences ;

: sum-of-squares ( seq -- n ) [ sq ] map-sum ;

{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares

FALSE

0 3 1 4 1 5 9$*\ [$0=~][$*+\]#%.

Fantom

class SumSquares
{
  static Int sumSquares (Int[] numbers)
  {
    Int sum := 0
    numbers.each |n| { sum += n * n }
    return sum
  }

  public static Void main () 
  {
    Int[] n := [,]
    echo ("Sum of squares of $n = ${sumSquares(n)}")
    n = [1,2,3,4,5]
    echo ("Sum of squares of $n = ${sumSquares(n)}")
  }
}

Fish

v
\0&
>l?!v:*&+&
    >&n;

Forth

: fsum**2 ( addr n -- f )
  0e
  dup 0= if 2drop exit then
  floats bounds do
    i f@ fdup f* f+
  1 floats +loop ;

create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fsum**2 f.     \ 133.

Fortran

In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic:

real, dimension(1000) :: a = (/ (i, i=1, 1000) /)
real, pointer, dimension(:) :: p => a(2:1)       ! pointer to zero-length array
real :: result, zresult

result = sum(a*a)    ! Multiply array by itself to get squares

result = sum(a**2)   ! Use exponentiation operator to get squares

zresult = sum(p*p)   ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected

FreeBASIC

' FB 1.05.0 Win64

Function SumSquares(a() As Double) As Double
  Dim As Integer length = UBound(a) - LBound(a) + 1
  If length = 0 Then Return 0.0
  Dim As Double sum = 0.0
  For i As Integer = LBound(a) To UBound(a)
    sum += a(i) * a(i)
  Next
  Return sum
End Function

Dim a(5) As Double = {1.0, 2.0, 3.0, -1.0, -2.0, -3.0}
Dim sum As Double = SumSquares(a())
Print "The sum of the squares is"; sum
Print 
Print "Press any key to quit"
Sleep
Output:
The sum of the squares is 28

Frink

f = {|x| x^2}   // Anonymous function which squares its argument
a = [1,2,3,5,7]
println[sum[map[f,a], 0]]

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Test cases

GAP

# Just multiplying a vector by itself yields the sum of squares (it's an inner product)
# It's necessary to check for the empty vector though
SumSq := function(v)
	if Size(v) = 0 then
		return 0;
	else
		return v*v;
	fi;
end;

GEORGE

read (n) print ;
0
1, n rep (i)
   read print dup mult +
   ]
print

data

11
 8
 12
 15
 6
 25
 19
 33
 27
 3
 37
 4

results:

 1.100000000000000E+0001  << number of values (11)
 8.000000000000000        << 11 data
 1.200000000000000E+0001
 1.500000000000000E+0001
 6.000000000000000      
 2.500000000000000E+0001
 1.900000000000000E+0001
 3.300000000000000E+0001
 2.700000000000000E+0001
 3.000000000000000      
 3.700000000000000E+0001
 4.000000000000000      
 4.667000000000000E+0003  << sum of squares

Go

Implementation
package main

import "fmt"

var v = []float32{1, 2, .5}

func main() {
    var sum float32
    for _, x := range v {
        sum += x * x
    }
    fmt.Println(sum)
}
Output:
5.25
Library
package main

import (
    "fmt"

    "github.com/gonum/floats"
)

var v = []float64{1, 2, .5}

func main() {
    fmt.Println(floats.Dot(v, v))
}
Output:
5.25

Golfscript

{0\{.*+}%}:sqsum;
# usage example
[1 2 3]sqsum puts

Groovy

def array = 1..3

// square via multiplication
def sumSq = array.collect { it * it }.sum()
println sumSq

// square via exponentiation
sumSq = array.collect { it ** 2 }.sum()

println sumSq
Output:
14
14

Haskell

Three approaches:

versions :: [[Int] -> Int]
versions =
  [ sum . fmap (^ 2)      -- ver 1
  , sum . ((^ 2) <$>)     -- ver 2
  , foldr ((+) . (^ 2)) 0 -- ver 3
  ]

main :: IO ()
main =
  mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions)
Output:
[133,91,0,1]
[133,91,0,1]
[133,91,0,1]

Icon and Unicon

procedure main()
   local lst
   lst := []
   #Construct a simple list and pass it to getsum
   every put(lst,seq()\2)
   write(getsum(lst))
end

procedure getsum(lst)
   local total
   total := 0
   every total +:= !lst ^ 2
   return total
end

IDL

print,total(array^2)

Inform 7

Sum Of Squares is a room.

To decide which number is the sum of (N - number) and (M - number) (this is summing):
	decide on N + M.

To decide which number is (N - number) squared (this is squaring):
	decide on N * N.

To decide which number is the sum of squares of (L - list of numbers):
	decide on the summing reduction of squaring applied to L.

When play begins:
	say the sum of squares of {};
	say line break;
	say the sum of squares of {1, 2, 3};
	end the story.

Io

list(3,1,4,1,5,9) map(squared) sum

J

ss=: +/ @: *:

That is, sum composed with square. The verb also works on higher-ranked arrays. For example:

   ss 3 1 4 1 5 9
133
   ss $0           NB. $0 is a zero-length vector
0
   x=: 20 4 ?@$ 0  NB. a 20-by-4 table of random (0,1) numbers
   ss x
9.09516 5.19512 5.84173 6.6916

The computation can also be written as a loop. It is shown here for comparison only and is highly non-preferred compared to the version above.

ss1=: 3 : 0
 z=. 0
 for_i. i.#y do. z=. z+*:i{y end.
)

   ss1 3 1 4 1 5 9
133
   ss1 $0
0
   ss1 x
9.09516 5.19512 5.84173 6.6916

Java

Works with: Java version 1.5+
public class SumSquares
{
 public static void main(final String[] args)
 {
  double sum = 0;
  int[] nums = {1,2,3,4,5};
  for (int i : nums)
   sum += i * i;
  System.out.println("The sum of the squares is: " + sum);
 }
}

JavaScript

ES5

function sumsq(array) {
  var sum = 0;
  var i, iLen;

  for (i = 0, iLen = array.length; i < iLen; i++) {
    sum += array[i] * array[i];
  }
  return sum;
}

alert(sumsq([1,2,3,4,5]));  // 55

An alternative using a while loop and Math.pow

function sumsq(array) {
  var sum = 0, 
      i = array.length;

  while (i--) sum += Math.pow(array[i], 2);

  return sum;
}

alert(sumsq([1,2,3,4,5])); // 55


Library: Functional
Functional.reduce("x+y*y", 0, [1,2,3,4,5])

map (JS 1.6) and reduce (JS 1.8)

[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; });

ES6

Two ways of composing a sumOfSquares function

(() => {
    'use strict';

    // sumOfSquares :: Num a => [a] -> a
    const sumOfSquares = xs =>
        sum(xs.map(squared));

    // sumOfSquares2 :: Num a => [a] -> a
    const sumOfSquares2 = xs =>
        xs.reduce((a, x) => a + squared(x), 0);


    // ---------------------- TEST -----------------------
    const main = () => [
        sumOfSquares,
        sumOfSquares2
    ].map(
        f => f([3, 1, 4, 1, 5, 9])
    ).join('\n');


    // --------------------- GENERIC ---------------------

    // squared :: Num a => a -> a
    const squared = x =>
        Math.pow(x, 2);

    // sum :: [Num] -> Num
    const sum = xs =>
        // The numeric sum of all values in xs.
        xs.reduce((a, x) => a + x, 0);

    // MAIN ---
    return main();
})();
Output:
133
133

Joy

[1 2 3 4 5] 0 [dup * +] fold.

jq

jq supports both arrays and streams, and so we illustrate how to handle both.

# ss for an input array:
def ss: map(.*.) | add;

# ss for a stream, S, without creating an intermediate array:
def ss(S): reduce S as $x (0; . + ($x * $x) );

We can also use a generic "SIGMA" filter that behaves like the mathematical SIGMA:

# SIGMA(exp) computes the sum of exp over the input array:
def SIGMA(exp): map(exp) | add;

# SIGMA(exp; S) computes the sum of exp over elements of the stream, S,
# without creating an intermediate array:
def SIGMA(exp; S): reduce (S|exp) as $x (0; . + $x);

Finally, a "mapreduce" filter:

def mapreduce(mapper; reducer; zero): 
  if length == 0 then zero
  else map(mapper) | reducer
  end;

Demonstration:

def demo(n):
  "ss:           \( [range(0;n)] | ss )",
  "ss(S):        \( ss( range(0;n) ) )",
  "SIGMA(.*.):   \( [range(0;n)] | SIGMA(.*.) )",
  "SIGMA(.*.;S): \( SIGMA( .*.; range(0;n) ) )",
  "mapreduce(.*.; add; 0): \( [range(0;n)] | mapreduce(.*.; add; 0) )"
;

demo(3) # 0^2 + 1^2 + 2^2
Output:
"ss:           5"
"ss(S):        5"
"SIGMA(.*.):   5"
"SIGMA(.*.;S): 5"
"mapreduce(.*.; add; 0): 5"

Julia

There are several easy ways to do this in Julia:

julia> sum([1,2,3,4,5].^2)
55

julia> sum([x^2 for x in [1,2,3,4,5]])
55

julia> mapreduce(x->x^2,+,[1:5])
55

julia> sum([x^2 for x in []])
0

K

  ss: {+/x*x}
  ss 1 2 3 4 5
55
  ss@!0
0

Kotlin

Kotlin functional capabilities make this easy. map can be used to transform the elements of any array, collection, iterable or sequence, and then sum can be used to compute the sum. So .map {it * it}.sum().

However, when the input is a collection, map will also output a collection. This can be wasteful not only in terms of computation, but also in terms of memory. Piping a .asSequence() first will make the operation lazy, making it faster, and less memory intensive. A Kotlin Sequence is the spiritual equivalent of Java’s Stream

Still, Sequences are not free either. Kotlin also offers reduce and fold to do the above in a single operation. This is actually much faster than the above 2 approaches.

Finally, a classic for-loop can also be used. Note that because forEach and fold are inline functions, these are actually exactly as efficient as the had-written for-loop.

import kotlin.random.Random
import kotlin.system.measureTimeMillis
import kotlin.time.milliseconds

enum class Summer {
    MAPPING {
        override fun sum(values: DoubleArray) = values.map {it * it}.sum()
    },
    SEQUENCING {
        override fun sum(values: DoubleArray) = values.asSequence().map {it * it}.sum()
    },
    FOLDING {
        override fun sum(values: DoubleArray) = values.fold(0.0) {acc, it -> acc + it * it}
    },
    FOR_LOOP {
        override fun sum(values: DoubleArray): Double {
            var sum = 0.0
            values.forEach { sum += it * it }
            return sum
        }
    },
    ;
    abstract fun sum(values: DoubleArray): Double
}

fun main() {
    run {
        val testArrays = listOf(
            doubleArrayOf(),
            doubleArrayOf(Random.nextInt(100) / 10.0),
            DoubleArray(6) { Random.nextInt(100) / 10.0 },
        )
        for (impl in Summer.values()) {
            println("Test with ${impl.name}:")
            for (v in testArrays) println("  ${v.contentToString()} -> ${impl.sum(v)}")
        }
    }
    
    run {
        val elements = 100_000
        val longArray = DoubleArray(elements) { Random.nextDouble(10.0) }

        for (impl in Summer.values()) {
            val time = measureTimeMillis {
                impl.sum(longArray)
            }.milliseconds
            println("Summing $elements with ${impl.name} takes: $time")
        }
        var acc = 0.0
        for (v in longArray) acc += v
    }
}
Output:
Test with MAPPING:
  [] -> 0.0
  [3.5] -> 12.25
  [9.9, 9.1, 3.6, 1.2, 0.9, 2.2] -> 200.87
Test with SEQUENCING:
  [] -> 0.0
  [3.5] -> 12.25
  [9.9, 9.1, 3.6, 1.2, 0.9, 2.2] -> 200.87
Test with FOLDING:
  [] -> 0.0
  [3.5] -> 12.25
  [9.9, 9.1, 3.6, 1.2, 0.9, 2.2] -> 200.87
Test with FOR_LOOP:
  [] -> 0.0
  [3.5] -> 12.25
  [9.9, 9.1, 3.6, 1.2, 0.9, 2.2] -> 200.87
Summing 100000 elements with MAPPING takes: 31.0ms
Summing 100000 elements with SEQUENCING takes: 13.0ms
Summing 100000 elements with FOLDING takes: 2.00ms
Summing 100000 elements with FOR_LOOP takes: 2.00ms

Lambdatalk

{def sumsq
 {lambda {:s}
  {+ {S.map {lambda {:i} {* :i :i}} :s}}}}
-> sumsq

{sumsq 1 2 3 4 5}
-> 55
{sumsq 0}
-> 0

Lang5

[1 2 3 4 5] 2 ** '+ reduce .

Lasso

define sumofsquares(values::array) => {

	local(sum = 0)

	with value in #values do {
		#sum += #value * #value
	}

	return #sum
}

sumofsquares(array(1,2,3,4,5))
Output:
55

LFE

(defun sum-sq (nums)
  (lists:foldl
    (lambda (x acc)
      (+ acc (* x x)))
    0 nums))

Usage:

> (sum-sq '(3 1 4 1 5 9))
133

Liberty BASIC

'   [RC] Sum of Squares

    SourceList$     ="3 1 4 1 5 9"
    'SourceList$     =""

    '   If saved as an array we'd have to have a flag for last data.
    '   LB has the very useful word$() to read from delimited strings.
    '   The default delimiter is a space character, " ".

    SumOfSquares    =0
    n               =0
    data$           ="666"  '   temporary dummy to enter the loop.

    while data$ <>""                                '   we loop until no data left.
        data$           =word$( SourceList$, n +1)  '   first data, as a string
        NewVal          =val( data$)                '   convert string to number
        SumOfSquares    =SumOfSquares +NewVal^2     '   add to existing sum of squares
        n =n +1                                     '   increment number of data items found
    wend

    n =n -1

    print "Supplied data was ";         SourceList$
    print "This contained ";            n; " numbers."
    print "Sum of squares is ";         SumOfSquares

    end

LiveCode

put "1,2,3,4,5" into nums
repeat for each item n in nums
    add (n * n) to m
end repeat
put m  // 55

print apply "sum map [? * ?] [1 2 3 4 5]  ; 55

Logtalk

sum(List, Sum) :-
    sum(List, 0, Sum).

sum([], Sum, Sum).
sum([X| Xs], Acc, Sum) :-
    Acc2 is Acc + X,
    sum(Xs, Acc2, Sum).

Lua

function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end
function squaresumt(t) return squaresum(unpack(t)) end

print(squaresumt{3, 5, 4, 1, 7})

M2000 Interpreter

M2000 use two concepts for arrays: standard array like A() and pointer to array as A. Pointer arithmetic not allowed here. Standard arrays are values types, and pointers are reference types. So we can handle an array both with pointer and without.

Dim A() 'make an array with zero items

A=(,) 'make a pointer to array with zero items

A=(1,) 'make a pointer to array with one item

A()=A 'make a copy of array pointed by A to A()

A=A() 'make A a pointer for A()

Dim A(10)=1 'redim A() and pass 1 to each item

k=lambda m=1->{=m:m++}  ' a lambda function with a closure m

Dim B(10)<<k()    'fill B() from 1 to 10

A()=B() ' copy B() to A(), A() object stay as is, but new items loaded, so pointer A points to A.

A+=100 ' add 100 to each element of A()

A(0)+=100 ' add 100 to first element

A()=Cons(A,A)

Now A and A() prints a 20 item array (Cons() add a list of arrays)
Print A   ' or Print A() print the same

And this is the task, using a lambda function (we can use a standard function, just use Function Square { code here })

Because M2000 modules and functions use stack for passing values, we use read statement to read a value. Functions in expressions has no return to stack because they have own stack, so passing values are filled in a fresh stack in every call. This not hold if we call function using Call (as a module), so stack is passed from parent (caller).

When we pass an array in stack, a pointer to array (to one of two interfaces) and depends the name type of a read to make this a copy or a pointer to array. So here we use: read a as a pointer to array (so it is a by reference pass). We can use Read a() and then a=a() (and remove Link a to a()), so we use by value pass, and that is a decision from callee, not the caller (this happen for objects)

Module Checkit {
      A=(1,2,3,4,5)
      Square=lambda -> {
            read a
            if len(a)=0 then =0: exit
            link a to a()
            \\ make sum same type as a(0)
            sum=a(0)-a(0)
            for i=0 to len(a)-1 {sum+=a(i)*a(i)}
            =sum
      }
      Print Square(a)=55
      Print Square((,))=0 ' empty  array
      Dim k(10)=2, L()
      Print Square(K())=40
      Print Square(L())=0
      A=(1@,2@,3@,4@,5@)
      X=Square(A)
      Print Type$(X)="Decimal", X=55@
}
Checkit

Maple

F := V -> add(v^2, v in V):
F(<1,2,3,4,5>);

Mathematica/Wolfram Language

As a function 1:

SumOfSquares[x_]:=Total[x^2]
SumOfSquares[{1,2,3,4,5}]

As a function 2:

SumOfSquares[x_]:=x.x
SumOfSquares[{1,2,3,4,5}]

Pure function 1: (postfix operator in the following examples)

{1,2,3,4,5} // Total[#^2] &

Pure function 2:

{1, 2, 3, 4, 5} // #^2 & // Total

Pure function 3:

{1, 2, 3, 4, 5} // #.#&

MATLAB

function [squaredSum] = sumofsquares(inputVector)
   squaredSum = sum( inputVector.^2 );

Maxima

nums : [3,1,4,1,5,9];
sum(nums[i]^2,i,1,length(nums));

or

nums : [3,1,4,1,5,9];
lsum(el^2, el, nums);

Mercury

:- module sum_of_squares.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list.

main(!IO) :-
    io.write_int(sum_of_squares([3, 1, 4, 1, 5, 9]), !IO),
    io.nl(!IO).

:- func sum_of_squares(list(int)) = int.

sum_of_squares(Ns) = list.foldl((func(N, Acc) = Acc + N * N), Ns, 0).

min

Works with: min version 0.19.3
((bool) ((dup *) (+) map-reduce) (pop 0) if) :sq-sum

(1 2 3 4 5) sq-sum puts
() sq-sum puts
Output:
55
0

MiniScript

sumOfSquares = function(seq)
    sum = 0
    for item in seq
        sum = sum + item*item
    end for
    return sum
end function

print sumOfSquares([4, 8, 15, 16, 23, 42])
print sumOfSquares([1, 2, 3, 4, 5])
print sumOfSquares([])
Output:
2854
55
0

МК-61/52

x^2	+	С/П	БП	00

Modula-3

MODULE SumSquares EXPORTS Main;

IMPORT IO, Fmt;

TYPE RealArray = ARRAY OF REAL;

PROCEDURE SumOfSquares(x: RealArray): REAL =
  VAR sum := 0.0;
  BEGIN
    FOR i := FIRST(x) TO LAST(x) DO
      sum := sum + x[i] * x[i];
    END;
    RETURN sum;
  END SumOfSquares;

BEGIN
  IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0})));
  IO.Put("\n");
END SumSquares.

MOO

@verb #100:sum_squares this none this rd
@program #100:sum_squares
sum = 0;
list = args[1];
for i in (list)
  sum = sum + (i^2);
endfor
player:tell(toliteral(list), " => ", sum);
.

{{out}}
;#100:sum_squares({3,1,4,1,5,9})
{3, 1, 4, 1, 5, 9} => 133
;#100:sum_squares({})
{} => 0

MUMPS

SUMSQUARE(X)
 ;X is assumed to be a list of numbers separated by "^"
 NEW RESULT,I
 SET RESULT=0,I=1
 FOR  QUIT:(I>$LENGTH(X,"^"))  SET RESULT=($PIECE(X,"^",I)*$PIECE(X,"^",I))+RESULT,I=I+1
 QUIT RESULT

Nanoquery

def sum_squares(vector)
        if len(vector) = 0
                return 0
        end

        sum = 0
        for n in vector
                sum += n ^ 2
        end
        return sum
end

println sum_squares({})
println sum_squares({1, 2, 3, 4, 5})
println sum_squares({10, 3456, 2, 6})
Output:
0
55
11944076

Nemerle

SS(x : list[double]) : double
{
    |[] => 0.0
    |_  => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_)
}

NetRexx

/*NetRexx *************************************************************
* program to sum the squares of a vector of fifteen numbers.
* translated from REXX
* 14.05.2013 Walter Pachl
**********************************************************************/
numeric digits 50                   /*allow 50-digit # (default is 9)*/
v='-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12' /* vector with some #s.     */
n=v.words()
x=''
sum=0                               /*initialize   SUM   to zero.    */
                                    /*if vector is empty, sum = zero.*/
loop Until x=''                     /*loop until list is exhausted   */
  Parse v x v                       /* pick next number              */
  If x>'' Then                      /* there is a number             */
    sum=sum + x**2                  /*add its square to the sum.     */
  end
say "The sum of" n "elements for the V vector is:" sum
Output:
The sum of 15 elements for the V vector is: 10650.25

NewLISP

(apply + (map (fn(x) (* x x)) '(3 1 4 1 5 9)))
-> 133
(apply + (map (fn(x) (* x x)) '()))
-> 0

Nim

import math, sequtils

proc sumSquares[T: SomeNumber](a: openArray[T]): T =
  sum(a.mapIt(it * it))

let a1 = [1, 2, 3, 4, 5]
echo a1, " → ", sumSquares(a1)

let a2: seq[float] = @[]
echo a2, " → ", sumSquares(a2)
Output:
[1, 2, 3, 4, 5] → 55
@[] → 0.0

Oberon-2

Translation of: Modula-3
MODULE SumSquares;

  IMPORT Out;

  VAR
    A1:ARRAY 6 OF REAL;

  PROCEDURE Init;
  BEGIN
    A1[0] := 3.0; A1[1] := 1.0; A1[2] := 4.0; A1[3] := 5.0; A1[4] := 9.0;
  END Init;
  
  PROCEDURE SumOfSquares(VAR arr:ARRAY OF REAL):REAL;
    VAR
      i:LONGINT;
      sum:REAL;
  BEGIN
    sum := 0.0;
    FOR i := 0 TO LEN(arr)-1 DO
      sum := sum + arr[i] * arr[i]
    END;
    RETURN sum
  END SumOfSquares;

BEGIN
  Init;
  Out.Real(SumOfSquares(A1),0);
  Out.Ln
END SumSquares.
Output:
1.32E+02

Objeck

bundle Default {
  class Sum {
    function : native : SquaredSum(values : Float[]) ~ Float {
       sum := 0.0;
       for(i := 0 ; i < values->Size()	; i += 1;) {
         sum += (values[i] * values[i]);
       };
       
       return sum;
    }

    function : Main(args : String[]) ~ Nil {
       SquaredSum([3.0, 1.0, 4.0, 1.0, 5.0, 9.0])->PrintLine();
     }
  }
}

OCaml

List.fold_left (fun sum a -> sum + a * a) 0 ints
List.fold_left (fun sum a -> sum +. a *. a) 0. floats

Octave

a = [1:10];
sumsq = sum(a .^ 2);

Oforth

#sq [1, 1.2, 3, 4.5 ] map sum

Ol

(define (sum-of-squares l)
   (fold + 0 (map * l l)))

(print (sum-of-squares '(1 2 3 4 5 6 7 8 9 10)))
; ==> 385

Order

#include <order/interpreter.h>

ORDER_PP(8to_lit(
  8seq_fold(8plus, 0,
            8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(3, 1, 4, 1, 5, 9)))
))

Oz

declare
  fun {SumOfSquares Xs}
     for X in Xs sum:S do
        {S X*X}
     end
  end
in
  {Show {SumOfSquares [3 1 4 1 5 9]}}

PARI/GP

Generic

It is possible to apply a function, in this case ^2 to each element of an iterable and sum the result:

ss(v)={
  sum(i=1,#v,v[i]^2)
};

Specific

For this particular task the product of a row matrix and its transpose is the sum of squares:

n=[2,5,23]
print(n*n~)
n=[]
print(n*n~)
Output:
558
0

Pascal

Works with: Free_Pascal
Library: Math

Example from the documenation of the run time library:

Program Example45;

{ Program to demonstrate the SumOfSquares function. }

Uses math;

Var
  I : 1..100;
  ExArray : Array[1..100] of Float;

begin
  Randomize;
  for I:=low(ExArray) to high(ExArray) do
    ExArray[i]:=(Random-Random)*100;
  Writeln('Max             : ',MaxValue(ExArray):8:4);
  Writeln('Min             : ',MinValue(ExArray):8:4);
  Writeln('Sum squares     : ',SumOfSquares(ExArray):8:4);
  Writeln('Sum squares (b) : ',SumOfSquares(@ExArray[1],100):8:4);
end.

Perl

sub sum_of_squares {
  my $sum = 0;
  $sum += $_**2 foreach @_;
  return $sum;
}

print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";

or

use List::Util qw(reduce);
sub sum_of_squares {
  reduce { $a + $b **2 } 0, @_;
}

print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";

Phix

function sum_of_squares(sequence s) return sum(sq_power(s,2)) end function
?apply({{},{3,1,4,1,5,9},tagset(10)},sum_of_squares)
Output:
{0,133,385}

Phixmonti

0 tolist
10 for 0 put endfor

0 swap len for
	get
	2 power rot + swap
endfor

drop print	/# 385 #/

PHP

function sum_squares(array $args) {
    return array_reduce(
        $args, create_function('$x, $y', 'return $x+$y*$y;'), 0
    );
}

In PHP5.3 support for anonymous functions was reworked. While the above code would still work, it is suggested to use

function sum_squares(array $args) {
    return array_reduce($args, function($x, $y) { 
        return $x+$y*$y;
    }, 0);
}

Usage for both examples: sum_squares(array(1,2,3,4,5)); // 55

Picat

go =>
  List = 1..666,
  println(sum_squares(List)),
  println(sum_squares([])),
  nl.

sum_squares([]) = 0.
sum_squares(List) = sum([I*I : I in List]).
Output:
98691321
0

PicoLisp

: (sum '((N) (* N N)) (3 1 4 1 5 9))
-> 133
: (sum '((N) (* N N)) ())
-> 0

PL/0

PL/0 has no arrays but they can be simulated.

const maxlist = 5;
var   sub, v, l1, l2, l3, l4, l5, sum;
procedure getelement;
begin
  if sub = 1 then v := l1;
  if sub = 2 then v := l2;
  if sub = 3 then v := l3;
  if sub = 4 then v := l4;
  if sub = 5 then v := l5;
end;
procedure setelement;
begin
  if sub = 1 then l1 := v;
  if sub = 2 then l2 := v;
  if sub = 3 then l3 := v;
  if sub = 4 then l4 := v;
  if sub = 5 then l5 := v;
end;
procedure sumofsquares;
begin
  sub := 0;
  sum := 0;
  while sub < maxlist do begin
    sub := sub + 1;
    call getelement;
    sum := sum + v * v
  end;
end;
begin
  sub := 0;
  while sub < maxlist do begin
    sub := sub + 1;
    v   := sub;
    call setelement;
  end;
  call sumofsquares;
  ! sum;
end.
Output:
55

PL/I

declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);

put (sum(A**2));

PL/M

Works with: 8080 PL/M Compiler

... under CP/M (or an emulator)

100H: /* CALCULATE THE SUM OF THE SQUARES OF THE ELEMENTS OF AN ARRAY       */

   /* CP/M BDOS SYSTEM CALL AND I/O ROUTINES                                */
   BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   PR$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C );  END;
   PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S );  END;
   PR$NL:     PROCEDURE;   CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
   PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
      V = N;
      W = LAST( N$STR );
      N$STR( W ) = '$';
      N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PR$STRING( .N$STR( W ) );
   END PR$NUMBER;

   /* TASK                                                                  */

   /* RETURNS THE SUM OF THE SQUARES OF THE ARRAY AT A$PTR, UB MUST BE THE  */
   /*         UB MUST BE THE UPPER-BOUND OF THE ARRAY                       */
   SUM$OF$SQUARES: PROCEDURE( A$PTR, UB )ADDRESS;
      DECLARE ( A$PTR, UB ) ADDRESS;
      DECLARE ( I, SUM    ) ADDRESS;
      DECLARE A BASED A$PTR ( 0 )ADDRESS;
      SUM = 0;
      DO I = 0 TO UB;
         SUM = SUM + ( A( I ) * A( I ) );
      END;
      RETURN SUM;
   END SUM$OF$SQUARES;

   DECLARE VALUES ( 5 )ADDRESS INITIAL( 1, 2, 3, 4, 5 );

   CALL PR$NUMBER( SUM$OF$SQUARES( .VALUES, LAST( VALUES ) ) );

EOF

Plain English

To run:
Start up.
Create a list.
Sum the squares of the list giving a ratio.
Destroy the list.
Write "Sum of squares: " then the ratio on the console.
Wait for the escape key.
Shut down.

An element is a thing with a ratio.

A list is some elements.

To add a ratio to a list:
Allocate memory for an element.
Put the ratio into the element's ratio.
Append the element to the list.

To create a list:
Add 3-1/10 to the list.
Add 1/1 to the list.
Add 4/1 to the list.
Add 1/1 to the list.
Add 5/1 to the list.
Add 9/1 to the list.

To sum the squares of a list giving a ratio:
Put 0 into the ratio.
Get an element from the list.
Loop.
If the element is nil, exit.
Add the element's ratio times the element's ratio to the ratio.
Put the element's next into the element.
Repeat.
Output:
Sum of squares: 133-61/100

Pop11

define sum_squares(v);
    lvars s = 0, j;
    for j from 1 to length(v) do
        s + v(j)*v(j) -> s;
    endfor;
    s;
enddefine;

sum_squares({1 2 3 4 5}) =>

PostScript

/sqrsum{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq
{}
{
x length{
/sum sum x i get 2 exp add def
/i i 1 add def
}repeat
}ifelse
sum ==
}def
Library: initlib
[3 1 4 1 5 9] 0 {dup * +} fold

PowerShell

function Get-SquareSum ($a) {
    if ($a.Length -eq 0) {
        return 0
    } else {
        $x = $a `
             | ForEach-Object { $_ * $_ } `
             | Measure-Object -Sum
        return $x.Sum
    }
}

Prolog

   sum([],0).
   sum([H|T],S) :- sum(T, S1), S is S1 + (H * H).

PureBasic

Procedure SumOfSquares(List base())
  ForEach base()
    Sum + base()*base()
  Next
  ProcedureReturn Sum
EndProcedure

Python

Using generator expression

sum(x * x for x in [1, 2, 3, 4, 5])
# or
sum(x ** 2 for x in [1, 2, 3, 4, 5])
# or
sum(pow(x, 2) for x in [1, 2, 3, 4, 5])

Functional versions:

# using lambda and map:
sum(map(lambda x: x * x, [1, 2, 3, 4, 5]))
# or 
sum(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
# or 
sum(map(lambda x: pow(x, 2), [1, 2, 3, 4, 5]))

# using pow and repeat
from itertools import repeat
sum(map(pow, [1, 2, 3, 4, 5], repeat(2)))

# using starmap and mul
from itertools import starmap
from operator import mul
a = [1, 2, 3, 4, 5]
sum(starmap(mul, zip(a, a)))

# using reduce
from functools import reduce
powers_of_two = (x * x for x in [1, 2, 3, 4, 5])
reduce(lambda x, y : x + y, powers_of_two)
# or
from operator import add
powers_of_two = (x * x for x in [1, 2, 3, 4, 5])
reduce(add, powers_of_two)
# or using a bit more complex lambda
reduce(lambda a, x: a + x*x, [1, 2, 3, 4, 5])

Using NumPy:

import numpy as np
a = np.array([1, 2, 3, 4, 5])
np.sum(a ** 2)

Q

ssq:{sum x*x}

Quackery

  [ 0 swap witheach [ 2 ** + ] ] is sumofsquares ( [ --> n )
Output:

Testing in the Quackery shell.

> quackery

Welcome to Quackery.

Enter "leave" to leave the shell.

/O> [ 0 swap witheach [ 2 ** + ] ] is sumofsquares
... ' [ 2 3 5 7 11 13 17 ] sumofsquares echo cr
... ' [ ] sumofsquares echo cr
... leave
... 
666
0

Sayonara.

R

arr <- c(1,2,3,4,5)
result <- sum(arr^2)

Racket

#lang racket
(for/sum ([x #(3 1 4 1 5 9)]) (* x x))

Raku

(formerly Perl 6)

say [+] map * ** 2, (3, 1, 4, 1, 5, 9);

If this expression seems puzzling, note that * ** 2 is equivalent to {$^x ** 2}— the leftmost asterisk is not the multiplication operator but the Whatever star, which specifies currying behavior. Another convenient way to distribute the exponentiation is via the cross metaoperator, which as a list infix is looser than comma in precedence but tighter than the reduction list operator:

say [+] <3 1 4 1 5 9> X** 2

Raven

define sumOfSqrs use $lst
   0 $lst each dup * +

[ 1 2 3 4] sumOfSqrs "Sum of squares: %d\n" print
Output:
Sum of squares: 30

Red

Red [
    date: 2021-10-25
    red-version: 0.6.4
    description: "Find the sum of squares of a numeric vector"
]

sum-squares: function [
    "Returns the sum of squares of all values in a block"
    values [any-list! vector!]
][
    result: 0
    foreach value values [result: value * value + result]
    result
]

print sum-squares []
print sum-squares [1 2 0.5]
Output:
0
5.25

Refal

$ENTRY Go {
    = <Prout <SquareSum 1 2 3 4 5>>
};

SquareSum {
    = 0;
    s.N e.rest = <+ <* s.N s.N> <SquareSum e.rest>>;
};
Output:
55

ReScript

With integers:

let sumOfSquares = (acc, item) => { acc + item * item }

Js.log(Js.Array2.reduce([10, 2, 4], sumOfSquares, 0))

With floats:

let sumOfSquares = (acc, item) => { acc +. item *. item }

Js.log(Js.Array2.reduce([10., 2., 4.], sumOfSquares, 0.))

REXX

input from pgm

/*REXX program  sums  the squares of the numbers  in a (numeric)  vector of 15 numbers. */
numeric digits 100                               /*allow 100─digit numbers; default is 9*/
v= -100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12          /*define a vector with fifteen numbers.*/
#=words(v)                                       /*obtain number of words in the V list.*/
$= 0                                             /*initialize the  sum  ($)  to zero.   */
       do k=1  for #                             /*process each number in the V vector. */
       $=$ + word(v,k)**2                        /*add a squared element to the ($) sum.*/
       end   /*k*/                               /* [↑]  if vector is empty, then sum=0.*/
                                                 /*stick a fork in it,  we're all done. */
say 'The sum of '      #      " squared elements for the  V  vector is: "   $

output   using an internal vector (list) of numbers:

The sum of  15  squared elements for the  V  vector is:  10650.25

input from C.L.

/*REXX program  sums  the squares of the numbers  in a (numeric)  vector of 15 numbers. */
numeric digits 100                               /*allow 100─digit numbers; default is 9*/
parse arg v                                      /*get optional numbers from the C.L.   */
if v=''  then v= -100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12      /*Not specified?  Use default*/
#=words(v)                                                 /*obtain number of words in V*/
say 'The vector of '    #     " elements is: "   space(v)  /*display the vector numbers.*/
$= 0                                             /*initialize the  sum  ($)  to zero.   */
             do  until v=='';   parse var v x v  /*process each number in the V vector. */
             $=$ + x**2                          /*add a squared element to the ($) sum.*/
             end   /*until*/                     /* [↑]  if vector is empty, then sum=0.*/
say                                              /*stick a fork in it,  we're all done. */
say 'The sum of '       #     " squared elements for the  V  vector is: "      $

output   using a vector (list) of numbers from the command line:

The vector of  10  elements is:  -1000 -100 -10 -1 0 +1 +10 100 1000 1e20

The sum of  10  squared elements for the  V  vector is:  10000000000000000000000000000000002020202

Ring

aList = [1,2,3,4,5]
see sumOfSquares(aList)

func sumOfSquares sos
sumOfSquares = 0
for i=1 to len(sos)
    sumOfSquares = sumOfSquares + pow(sos[i],2)
next
return sumOfSquares

RPL

Zero-length vectors don't exist in RPL, so there's no need to tackle this case:

≪ DUP DOT ≫ '∑SQV' STO

If we really need zero-length objects, we can use lists:

≪ 0 SWAP
   IF DUP SIZE THEN  
      1 OVER SIZE FOR j
         DUP j GET SQ + NEXT
   END DROP
≫ '∑SQL' STO

Using RPL 1993:

IF DUP SIZE THEN SQ ∑LIST ELSE SIZE END ≫ '∑SQL' STO
[ 1 2 3 4 5 ] ∑SQV
{ 1 2 3 4 5 } ∑SQL
{ } ∑SQL
Output:
3: 55
2: 55
1: 0

Ruby

[3,1,4,1,5,9].sum(0){|x| x*x}

Run BASIC

list$ = "1,2,3,4,5"
print sumOfSquares(list$)

FUNCTION sumOfSquares(sos$)
  while word$(sos$,i+1,",") <> ""
    i = i + 1
    sumOfSquares = sumOfSquares + val(word$(sos$,i,","))^2
  wend
END FUNCTION

Rust

fn sq_sum(v: &[f64]) -> f64 {
    v.iter().fold(0., |sum, &num| sum + num*num)
}

fn main() {
    let v = vec![3.0, 1.0, 4.0, 1.0, 5.5, 9.7];
    println!("{}", sq_sum(&v));

    let u : Vec<f64> = vec![];
    println!("{}", sq_sum(&u));
}

Sather

class MAIN is

  sqsum(s, e:FLT):FLT is
    return s + e*e;
  end;

  sum_of_squares(v :ARRAY{FLT}):FLT is
    return (#ARRAY{FLT}(|0.0|).append(v)).reduce(bind(sqsum(_,_)));
  end;

  main is
    v :ARRAY{FLT} := |3.0, 1.0, 4.0, 1.0, 5.0, 9.0|;
    #OUT + sum_of_squares(v) + "\n";
  end;

end;

Scala

Unfortunately there is no common "Numeric" class that Int and Double both extend, since Scala's number representation maps closely to Java's. Those concerned about precision can define a similar procedure for integers.

def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x}

Scheme

(define (sum-of-squares l)
  (apply + (map * l l)))
> (sum-of-squares (list 3 1 4 1 5 9))
133

Seed7

$ include "seed7_05.s7i";
  include "float.s7i";
 
const array float: list1 is [] (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
const array float: list2 is 0 times 0.0;

const func float: squaredSum (in array float: floatList) is func
  result
    var float: sum is 0.0;
  local
    var float: number is 0.0;
  begin
    for number range floatList do
      sum +:= number ** 2;
    end for;
  end func;
 
const proc: main is func
  begin
    writeln(squaredSum(list1));
    writeln(squaredSum(list2));
  end func;

Sidef

func sum_of_squares(vector) {
    var sum = 0;
    vector.each { |n| sum += n**2 };
    return sum;
}

say sum_of_squares([]);         # 0
say sum_of_squares([1,2,3]);    # 14

Slate

{1. 2. 3} reduce: [|:x :y| y squared + x].
{} reduce: [|:x :y| y squared + x] ifEmpty: [0].

Smalltalk

#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared]

SNOBOL4

Works with: Macro Spitbol
Works with: Snobol4+
Works with: CSnobol
        define('ssq(a)i') :(ssq_end)
ssq     i = i + 1; ssq = ssq + (a<i> * a<i>) :s(sumsq)f(return)
ssq_end

*       # Fill array, test and display
        str = '1 2 3 5 7 11 13 17 19 23'; a = array(10)
loop    i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
        output = str ' -> ' sumsq(a)
end
Output:
 1 2 3 5 7 11 13 17 19 23 -> 1557

SQL

select sum(x*x) from vector

Note that this assumes that the values in our vector are named x.

Standard ML

foldl (fn (a, sum) => sum + a * a) 0 ints
foldl (fn (a, sum) => sum + a * a) 0.0 reals

Stata

Mata

a = 1..100
sum(a:^2)
  338350

a = J(0, 1, .)
length(a)
  0
sum(a:^2)
  0

Swift

func sumSq(s: [Int]) -> Int {
  return s.map{$0 * $0}.reduce(0, +)
}

Tailspin

templates ssq
  when <[](0)> do 0 !
  otherwise $... -> $*$ -> ..=Sum&{of: :()} !
end ssq

[] -> ssq -> !OUT::write // outputs 0
[1..5] -> ssq -> !OUT::write // outputs 55

Tcl

package require Tcl 8.6
namespace path ::tcl::mathop

# {*} is like apply in Scheme--it turns a list into multiple arguments
proc sum_of_squares lst {
    + {*}[lmap x $lst {* $x $x}]
}
puts [sum_of_squares {1 2 3 4}]; # ==> 30
puts [sum_of_squares {}];        # ==> 0

Trith

[3 1 4 1 5 9] 0 [dup * +] foldl

TUSCRIPT

$$ MODE TUSCRIPT
array="3'1'4'1'5'9",sum=0
LOOP a=array
sum=sum+(a*a)
ENDLOOP
PRINT sum
Output:
133 

UnixPipes

folder() {
   (read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res)
}

fold() {
   (while read a ; do
       fold | folder $a
   done)
}


(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold

UNIX Shell

sum_squares () {
        _r=0
        for _n
        do
                : "$((_r += _n * _n))"
        done
        echo "$_r"
}

sum_squares 3 1 4 1 5 9
Output:
133

Ursala

The ssq function defined below zips two copies of its argument together, maps the product function to all pairs, and then sums the result by way of the reduction operator, -:.

#import nat

ssq = sum:-0+ product*iip

#cast %n

main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93>
Output:
62223

V

[sumsq [dup *] map 0 [+] fold].

[] sumsq
=0
[1 2 3] sumsq
=14

VBA

Public Sub sum_of_squares()
    Debug.Print WorksheetFunction.SumSq([{1,2,3,4,5,6,7,8,9,10}])
End Sub
Output:
 385 

VBScript

Function sum_of_squares(arr)
	If UBound(arr) = -1 Then
		sum_of_squares = 0
	End If
	For i = 0 To UBound(arr)
		sum_of_squares = sum_of_squares + (arr(i)^2)
	Next
End Function

WScript.StdOut.WriteLine sum_of_squares(Array(1,2,3,4,5))
WScript.StdOut.WriteLine sum_of_squares(Array())
Output:
55
0

Visual Basic .NET

 Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer
        If i Is Nothing OrElse i.Count = 0 Then
            Return 0
        End If
        Return i.[Select](Function(x) x * x).Sum()
 End Function

 Private Shared Sub Main()
        Dim a As Integer() = New Integer() {1, 2, 3, 4, 5}
        ' 55
        Console.WriteLine(sumsq(a))
 
        For K As Integer = 0 To 16
               Console.WriteLine("SumOfSquares({0}) = {1}", K, SumOfSquares(K))
        Next
 End Sub
 Function SumOfSquares(ByVal Max As Integer)
        Dim Square As Integer = 0
        Dim Add As Integer = 1
        Dim Sum As Integer = 0
        For J As Integer = 0 To Max - 1
            Square += Add
            Add += 2
            Sum += Square
        Next
        Return Sum
 End Function

 Function SumOfSquaresByMult(ByVal Max As Integer)
        Dim Sum As Integer = 0
        For J As Integer = 1 To Max
            Sum += J * J
        Next
        Return Sum
 End Function
Output:
55
SumOfSquares(0) = 0
SumOfSquares(1) = 1
SumOfSquares(2) = 5
SumOfSquares(3) = 14
SumOfSquares(4) = 30
SumOfSquares(5) = 55
SumOfSquares(6) = 91
SumOfSquares(7) = 140
SumOfSquares(8) = 204
SumOfSquares(9) = 285
SumOfSquares(10) = 385
SumOfSquares(11) = 506
SumOfSquares(12) = 650
SumOfSquares(13) = 819
SumOfSquares(14) = 1015
SumOfSquares(15) = 1240
SumOfSquares(16) = 1496

VTL-2

1000 :1)=1
1010 :2)=2
1020 :3)=3
1030 :4)=4
1040 :5)=5
1050 L=5
1060 #=2000
1070 ?=S
1080 #=9999
2000 R=!
2010 S=0
2020 I=1
2030 #=I<L+(I=L)=0*R
2040 S=I*I+S
2050 I=I+1
2060 #=2030
Output:
55

Wortel

@sum !*^@sq [3 1 4 1 5 9] ; returns 133
@sum !*^@sq [] ; returns 0

As a function:

^(@sum *^@sq)

Iterative function:

&a [@var sum 0 @for x of a :!+sum *x x sum]

Wren

var sumSquares = Fn.new { |v| v.reduce(0) { |sum, n| sum + n * n } }

var v = [1, 2, 3, -1, -2, -3]
System.print("Vector         : %(v)")
System.print("Sum of squares : %(sumSquares.call(v))")
Output:
Vector         : [1, 2, 3, -1, -2, -3]
Sum of squares : 28

XLISP

The task specification calls for a function that takes a numeric vector. If you want a function that takes a linked list (which would be more idiomatic), just extract the inner function SUMSQ and use that instead of SUM-OF-SQUARES.

(defun sum-of-squares (vec)
    (defun sumsq (xs)
        (if (null xs)
            0
            (+ (expt (car xs) 2) (sumsq (cdr xs)))))
    (sumsq (vector->list vec)))

(define first-seven-primes #(2 3 5 7 11 13 17))

(define zero-length-vector #())

(print `(the sum of the squares of the first seven prime numbers is ,(sum-of-squares first-seven-primes)))

(print `(the sum of the squares of no numbers at all is ,(sum-of-squares zero-length-vector)))
Output:
(THE SUM OF THE SQUARES OF THE FIRST SEVEN PRIME NUMBERS IS 666) 
(THE SUM OF THE SQUARES OF NO NUMBERS AT ALL IS 0)

XPL0

include c:\cxpl\codes;  \intrinsic 'code' declarations

func SumSq(V, L);
int  V, L;
int  S, I;
[S:= 0;
for I:= 0 to L-1 do S:= S+sq(V(I));
return S;
]; \SumSq

[IntOut(0, SumSq([1,2,3,4,5,6,7,8,9,10], 10));  CrLf(0);
 IntOut(0, SumSq([0], 0));  CrLf(0);    \zero-length vector "[]" doesn't compile
]
Output:
385
0

zkl

T().reduce(fcn(p,n){ p + n*n },0)               //-->0
T(3,1,4,1,5,9).reduce(fcn(p,n){ p + n*n },0.0) //-->133.0
[1..5].reduce(fcn(p,n){ p + n*n },0)          //-->55