Sum of squares: Difference between revisions

Content deleted Content added
Added an Algol W sample
Miks1965 (talk | contribs)
PascalABC.NET
 
(145 intermediate revisions by 67 users not shown)
Line 1:
{{task|Arithmetic operations}}
Write a program to find the sum of squares of a numeric vector. <br>
The program should work on a zero-length vector (with an answer of 0).
 
;Task:
See also [[Mean]].
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 &nbsp; '''0''').
 
 
;Related task:
* &nbsp; [[Mean]]
<br><br>
 
=={{header|0815}}==
<syntaxhighlight lang="0815">
{x{*%<:d:~$<:1:~>><:2:~>><:3:~>><:4:~>><:5:~>><:6:~>><:7:
~>><:8:~>><:9:~>><:a:~>><:b:~>><:c:~>><:ffffffffffffffff:
~>{x{*>}:8f:{x{*&{=+>{~>&=x<:ffffffffffffffff:/#:8f:{{~%
</syntaxhighlight>
{{out}}
<pre>
0
28A
</pre>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">print(sum([1, 2, 3, 4, 5].map(x -> x^2)))</syntaxhighlight>
 
{{out}}
<pre>
55
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* 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</syntaxhighlight>
{{out}}
<pre>
The sum of squares is: 385
</pre>
 
=={{header|8086 Assembly}}==
 
<syntaxhighlight lang="asm"> ;;; 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</syntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun sum-of-squares (xs)
(if (endp xs)
0
(+ (* (first xs) (first xs))
(sum-of-squares (rest xs)))))</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function sumOfSquares(vector:Vector.<Number>):Number
{
var sum:Number = 0;
Line 19 ⟶ 189:
sum += vector[i]*vector[i];
return sum;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Sum_Of_Squares is
Line 39 ⟶ 209:
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;</langsyntaxhighlight>
{{out}}
<pre>
Line 45 ⟶ 215:
1.33000E+02
</pre>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">real
squaredsum(list l)
{
Line 53 ⟶ 224:
 
s = 0;
i = -l_length(~l);
while (i) {
s += sq(l[i += 1]);
}
 
return s;
}
 
Line 66 ⟶ 237:
list l;
 
l = l_effectlist(0, 1, 2, 3);
 
o_form("~\n", squaredsum(l));
o_form("~\n", squaredsum(l_effectlist()));
o_form("~\n", squaredsum(l_effectlist(.5, -.5, 2)));
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>14
0
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}}==
Line 87 ⟶ 284:
 
The computation can be written as a loop.
<langsyntaxhighlight lang="algol68">PROC sum of squares = ([]REAL argv)REAL:(
REAL sum := 0;
FOR i FROM LWB argv TO UPB argv DO
Line 96 ⟶ 293:
test:(
printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));
)</langsyntaxhighlight>
{{out}}
<pre>
Line 104 ⟶ 301:
 
{{trans|python}}
<langsyntaxhighlight lang="algol68">[]REAL data = (3, 1, 4, 1, 5, 9);
 
PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL:
Line 119 ⟶ 316:
sum := 0;
printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data ))
)</langsyntaxhighlight>
{{out}}
<pre>
133
133
</pre>
{{works with|ALGOL 68|Revision 1 - requires the Currying extension}}
 
{{works with|ALGOL 68G|Any - tested with release a68g-2.8.3}}
 
{{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.
<syntaxhighlight lang="algol68">#!/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))
)</syntaxhighlight>
{{out}}
<pre>
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
</pre>
 
=={{header|ALGOL W}}==
 
<lang algolw>begin
===Using a dedicated % procedure to "sum the elements of a vector. As thesquares" procedure can't find %===
 
% 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 ( * )
; integer value lb
Line 146 ⟶ 405:
r_format := "A"; r_w := 10; r_d := 1; % set fixed point output %
write( sumSquares( numbers, 1, 5 ) );
end.</langsyntaxhighlight>
 
===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}}==
 
<langsyntaxhighlight Alorelang="alore">def sum_squares(a)
var sum = 0
for i in a
Line 159 ⟶ 444:
 
WriteLn(sum_squares([3,1,4,1,5,9]))
end</langsyntaxhighlight>
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl"> square_sum←{+/2*⍨⍵2}
square_sum 1 2 3 4 5
55
square_sum ⍬ ⍝The empty vector
0</langsyntaxhighlight>
 
=={{header|AppleScript}}==
 
Two ways of composing a sumOfSquares function:
<syntaxhighlight lang="applescript">------ 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</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{133.0, 133.0}</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">arr: 1..10
 
print sum map arr [x][x^2]</syntaxhighlight>
 
{{out}}
 
<pre>385</pre>
 
=={{header|Astro}}==
<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}}==
<langsyntaxhighlight lang="autohotkey">list = 3 1 4 1 5 9
Loop, Parse, list, %A_Space%
sum += A_LoopField**2
MsgBox,% sum</langsyntaxhighlight>
 
=={{header|AWK}}==
Vectors are read, space-separated, from stdin; sum of squares goes to stdout. The empty line produces 0.
<langsyntaxhighlight lang="awk">$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}'
3 1 4 1 5 9
133
 
0</langsyntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QBasic}}
Assume the numbers are in an array called <code>a</code>.
<langsyntaxhighlight lang="qbasic">sum = 0
FOR I = LBOUND(a) TO UBOUND(a)
sum = sum + a(I) ^ 2
NEXT I
PRINT "The sum of squares is: " + sum</langsyntaxhighlight>
 
==={{header|BBC BASICBaCon}}===
<syntaxhighlight lang="freebasic">' 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)</syntaxhighlight>
 
{{out}}
<pre>prompt$ ./sumsquares
385
prompt$ ./sumsquares -s 1000
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}}===
BBC BASIC cannot have a zero-length array.
<langsyntaxhighlight lang="bbcbasic"> DIM vector(5)
vector() = 1, 2, 3, 4, 5, 6
PRINT "Sum of squares = " ; MOD(vector()) ^ 2</langsyntaxhighlight>
{{out}}
<pre>Sum of squares = 91</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="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</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}}==
<langsyntaxhighlight lang="bc">define s(a[], n) {
auto i, s
Line 209 ⟶ 683:
return(s)
}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="bracmat">( ( sumOfSquares
= sum component
. 0:?sum
Line 224 ⟶ 720:
& out$(sumOfSquares$(3 4 i*5))
& out$(sumOfSquares$(a b c))
);</langsyntaxhighlight>
{{out}}
<pre>25
Line 231 ⟶ 727:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 } #Prints 385</langsyntaxhighlight>
 
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
double squaredsum(double *l, int e)
Line 253 ⟶ 749:
printf("%lf\n", squaredsum(NULL, 0));
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">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
}
}</syntaxhighlight>
 
=={{header|C++}}==
===Using accumulate===
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
#include <vector>
Line 281 ⟶ 798:
std::cout << vec_add_squares(v) << std::endl;
return 0;
}</langsyntaxhighlight>
===Using inner_product===
<syntaxhighlight lang="cpp">#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;
}</syntaxhighlight>
 
Alternative===Using version using {{libheader|Boost.Lambda}}:===
{{libheader|Boost.Lambda}}
<lang cpp>#include <numeric>
<syntaxhighlight lang="cpp">#include <numeric>
#include <vector>
#include "boost/lambda/lambda.hpp"
Line 293 ⟶ 828:
 
return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2);
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<lang csharp>using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
static int sumsq(ICollection<int> i) {
if (i == null || i.Count == 0) return 0;
return i.Select(x => x * x).Sum();
}
 
static void Main() {
int[] a = { 1, 2, 3, 4, 5 };
Console.WriteLine(sumsq(a)); // 55
}
}</lang>
 
=={{header|Chef}}==
<langsyntaxhighlight Cheflang="chef">Sum of squares.
 
First input is length of vector, then rest of input is vector.
Line 336 ⟶ 853:
Serves 1.
 
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn sum-of-squares [v]
(reduce #(+ %1 (* %2 %2)) 0 v))</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="coffeescript">
sumOfSquares = ( list ) ->
list.reduce (( sum, x ) -> sum + ( x * x )), 0
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun sum-of-squares (vector)
(loop for x across vector sum (expt x 2)))</langsyntaxhighlight>
 
Or in a functional way:
<syntaxhighlight lang="lisp">(defun sum-of-squares (vec)
(reduce #'+ (map 'vector (lambda (x) (* x x)) vec)))</syntaxhighlight>
 
=={{header|Cowgol}}==
 
<syntaxhighlight lang="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();</syntaxhighlight>
 
{{out}}
 
<pre>$ ./sumsq.386
0
$ ./sumsq.386 {1..30}
9455
$ ./sumsq.386 512
262144</pre>
 
=={{header|Crystal}}==
 
<syntaxhighlight lang="ruby">
def sum_squares(a)
a.map{|e| e*e}.sum()
end
 
puts sum_squares([1, 2, 3])
# => 14
</syntaxhighlight>
 
=={{header|D}}==
===Iterative Version===
<langsyntaxhighlight lang="d">T sumSquares(T)(T[] a) pure nothrow @safe @nogc {
T sum = 0;
foreach (e; a)
Line 366 ⟶ 967:
 
[3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>133.61</pre>
 
===Polymorphic Functional Style===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.traits, std.range;
 
auto sumSquares(Range)(Range data) pure nothrow @safe @nogc {
Line 381 ⟶ 982:
items.sumSquares.writeln;
10.iota.sumSquares.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>133.61
Line 388 ⟶ 989:
=={{header|Dart}}==
===Iterative Version===
<langsyntaxhighlight lang="d">sumOfSquares(list) {
var sum=0;
list.forEach((var n) { sum+=(n*n); });
Line 398 ⟶ 999:
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 405 ⟶ 1,006:
 
===Functional Style Version===
<langsyntaxhighlight lang="d">num sumOfSquares(List<num> l) => l.map((num x)=>x*x)
.fold(0, (num p,num n)=> p + n);
 
Line 412 ⟶ 1,013:
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 420 ⟶ 1,021:
=={{header|Delphi}}==
Delphi has standard SumOfSquares function in Math unit:
<langsyntaxhighlight Delphilang="delphi">program SumOfSq;
 
{$APPTYPE CONSOLE}
Line 440 ⟶ 1,041:
Writeln(SumOfSquares(A):6:2); // 30.00
Readln;
end.</langsyntaxhighlight>
 
=={{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}}==
 
<langsyntaxhighlight lang="e">def sumOfSquares(numbers) {
var sum := 0
for x in numbers {
Line 450 ⟶ 1,080:
}
return sum
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
nums[] = [ 1 2 3 4 5 ]
for v in nums[]
sum += v * v
.
print sum
</syntaxhighlight>
 
=={{header|Eiffel}}==
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 487 ⟶ 1,126:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">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))
}</syntaxhighlight>
{{out}}
<pre>
2854
55
0
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end)
133</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(defun sum-of-squares (numbers)
(apply #'+ (mapcar (lambda (k) (* k k)) numbers)))
 
(sum-of-squares (number-sequence 0 3)) ;=> 14</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="euphoria">function SumOfSquares(sequence v)
atom sum
sum = 0
Line 504 ⟶ 1,192:
end for
return sum
end function</langsyntaxhighlight>
 
=={{header|Excel}}==
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)
</syntaxhighlight>
</lang>
 
The above expression will return zero if there are no values in any cell.
 
<syntaxhighlight lang="text">
12 3 5 23 13 67 15 9 4 2
5691
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<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</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|FALSE}}==
<syntaxhighlight lang="false">
<lang FALSE>
0 3 1 4 1 5 9$*\ [$0=~][$*+\]#%.
</syntaxhighlight>
</lang>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
class SumSquares
{
Line 552 ⟶ 1,244:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fish}}==
<syntaxhighlight lang="fish">v
<lang Fish>v
\0&
>l?!v:*&+&
>&n;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: fsum**2 ( addr n -- f )
0e
dup 0= if 2drop exit then
Line 569 ⟶ 1,261:
 
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fsum**2 f. \ 133.</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic:
<langsyntaxhighlight lang="fortran">real, dimension(1000) :: a = (/ (i, i=1, 1000) /)
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real :: result, zresult
Line 581 ⟶ 1,273:
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</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
<pre>
The sum of the squares is 28
</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
f = {|x| x^2} // Anonymous function which squares its argument
a = [1,2,3,5,7]
println[sum[map[f,a], 0]]
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sum_of_squares}}
 
'''Solution'''
 
[[File:Fōrmulæ - Sum of squares 01.png]]
 
'''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|F_Sharp|F#}}==
<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>
=={{header|GAP}}==
<langsyntaxhighlight 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
SumSq := function(v)
Line 602 ⟶ 1,338:
return v*v;
fi;
end;</langsyntaxhighlight>
 
=={{header|GEORGE}}==
<langsyntaxhighlight GEORGElang="george">read (n) print ;
0
1, n rep (i)
read print dup mult +
]
print</langsyntaxhighlight>
data
<pre>
Line 644 ⟶ 1,380:
 
=={{header|Go}}==
;Implementation
<lang go>package main
<syntaxhighlight lang="go">package main
 
import "fmt"
 
var v = []float32{1, 2, .5}
 
func main() {
var sum float32
for _, x := range []float32{1,2,.5}v {
sum += x * x
}
fmt.Println(sum)
}</langsyntaxhighlight>
{{out}}
<pre>
5.25
</pre>
;Library
<syntaxhighlight lang="go">package main
 
import (
"fmt"
 
"github.com/gonum/floats"
)
 
var v = []float64{1, 2, .5}
 
func main() {
fmt.Println(floats.Dot(v, v))
}</syntaxhighlight>
{{out}}
<pre>
5.25
</pre>
 
=={{header|Golfscript}}==
<langsyntaxhighlight lang="golfscript">{0\{.*+}%}:sqsum;
# usage example
[1 2 3]sqsum puts</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def array = 1..3
 
// square via multiplication
Line 671 ⟶ 1,432:
sumSq = array.collect { it ** 2 }.sum()
 
println sumSq</langsyntaxhighlight>
 
{{out}}
Line 678 ⟶ 1,439:
 
=={{header|Haskell}}==
Three approaches:
<lang haskell>sumOfSquares = sum . map (^ 2)
<syntaxhighlight lang="haskell">versions :: [[Int] -> Int]
versions =
[ sum . fmap (^ 2) -- ver 1
, sum . ((^ 2) <$>) -- ver 2
, foldr ((+) . (^ 2)) 0 -- ver 3
]
 
main :: IO ()
> sumOfSquares [3,1,4,1,5,9]
main =
133</lang>
mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions)</syntaxhighlight>
 
=={{header|IDLOut}}==
<pre>[133,91,0,1]
 
[133,91,0,1]
<lang idl>print,total(array^2)</lang>
[133,91,0,1]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main()
local lst
lst := []
Line 701 ⟶ 1,469:
every total +:= !lst ^ 2
return total
end</langsyntaxhighlight>
 
=={{header|IDL}}==
 
<syntaxhighlight lang="idl">print,total(array^2)</syntaxhighlight>
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Sum Of Squares is a room.
 
To decide which number is the sum of (N - number) and (M - number) (this is summing):
Line 719 ⟶ 1,491:
say line break;
say the sum of squares of {1, 2, 3};
end the story.</langsyntaxhighlight>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">list(3,1,4,1,5,9) map(squared) sum</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">ss=: +/ @: *:</langsyntaxhighlight>
 
That is, sum composed with square. The verb also works on higher-ranked arrays. For example:
 
<langsyntaxhighlight lang="j"> ss 3 1 4 1 5 9
133
ss $0 NB. $0 is a zero-length vector
Line 736 ⟶ 1,508:
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</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="j">ss1=: 3 : 0
z=. 0
for_i. i.#y do. z=. z+*:i{y end.
Line 751 ⟶ 1,523:
0
ss1 x
9.09516 5.19512 5.84173 6.6916</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class SumSquares
{
public static void main(final String[] args)
Line 765 ⟶ 1,537:
System.out.println("The sum of the squares is: " + sum);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
===ES5===
<lang javascript>function sumsq(array) {
<syntaxhighlight lang="javascript">function sumsq(array) {
var sum = 0;
var i, iLen;
Line 778 ⟶ 1,551:
}
 
alert(sumsq([1,2,3,4,5])); // 55</langsyntaxhighlight>
 
An alternative using a while loop and Math.pow
 
<langsyntaxhighlight lang="javascript">function sumsq(array) {
var sum = 0,
i = array.length;
Line 791 ⟶ 1,564:
}
 
alert(sumsq([1,2,3,4,5])); // 55</langsyntaxhighlight>
 
 
{{libheader|Functional}}<langsyntaxhighlight lang="javascript">Functional.reduce("x+y*y", 0, [1,2,3,4,5])</langsyntaxhighlight>
 
map (JS 1.6) and reduce (JS 1.8)
 
<langsyntaxhighlight lang="javascript">[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; });</langsyntaxhighlight>
 
===ES6===
 
Two ways of composing a sumOfSquares function
<syntaxhighlight lang="javascript">(() => {
'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();
})();</syntaxhighlight>
{{Out}}
<pre>133
133</pre>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">[1 2 3 4 5] 0 [dup * +] fold.</syntaxhighlight>
 
=={{header|jq}}==
jq supports both arrays and streams, and so we illustrate how to handle both.
<langsyntaxhighlight lang="jq"># 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) );</langsyntaxhighlight>We can also use a generic "SIGMA" filter that behaves like the mathematical SIGMA:<langsyntaxhighlight lang="jq">
# SIGMA(exp) computes the sum of exp over the input array:
def SIGMA(exp): map(exp) | add;
Line 812 ⟶ 1,630:
# 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);</langsyntaxhighlight>
Finally, a "mapreduce" filter:<langsyntaxhighlight lang="jq">
def mapreduce(mapper; reducer; zero):
if length == 0 then zero
else map(mapper) | reducer
end;
</syntaxhighlight>
</lang>
Demonstration:<langsyntaxhighlight lang="jq">def demo(n):
"ss: \( [range(0;n)] | ss )",
"ss(S): \( ss( range(0;n) ) )",
Line 827 ⟶ 1,645:
;
 
demo(3) # 0^2 + 1^2 + 2^2</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="jq">"ss: 5"
"ss(S): 5"
"SIGMA(.*.): 5"
"SIGMA(.*.;S): 5"
"mapreduce(.*.; add; 0): 5"</langsyntaxhighlight>
 
=={{header|Julia}}==
There are several easy ways to do this in Julia:
<langsyntaxhighlight lang="julia">julia> sum([1,2,3,4,5].^2)
55
 
Line 847 ⟶ 1,665:
 
julia> sum([x^2 for x in []])
0</langsyntaxhighlight>
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang k>
ss: {+/x*x}
ss 1 2 3 4 5
Line 856 ⟶ 1,674:
ss@!0
0
</syntaxhighlight>
</lang>
 
=={{header|Lang5Kotlin}}==
Kotlin functional capabilities make this easy. <code>map</code> can be used to transform the elements of any array, collection, iterable or sequence, and then <code>sum</code> can be used to compute the sum. So <code>.map {it * it}.sum()</code>.
<lang lang5>[1 2 3 4 5] 2 ** '+ reduce .</lang>
 
However, when the input is a collection, <code>map</code> will also output a collection. This can be wasteful not only in terms of ''computation'', but also in terms of ''memory''. Piping a <code>.asSequence()</code> first will make the operation lazy, making it faster, and less memory intensive. A Kotlin <code>Sequence</code> is the spiritual equivalent of Java’s <code>Stream</code>
 
Still, Sequences are not free either. Kotlin also offers <code>reduce</code> and <code>fold</code> 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 <code>forEach</code> and <code>fold</code> are inline functions, these are actually exactly as efficient as the had-written for-loop.
 
<syntaxhighlight lang="kotlin">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
}
}</syntaxhighlight>
 
{{out}}
<pre>
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
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def sumsq
{lambda {:s}
{+ {S.map {lambda {:i} {* :i :i}} :s}}}}
-> sumsq
 
{sumsq 1 2 3 4 5}
-> 55
{sumsq 0}
-> 0
</syntaxhighlight>
 
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">[1 2 3 4 5] 2 ** '+ reduce .</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define sumofsquares(values::array) => {
 
local(sum = 0)
Line 874 ⟶ 1,790:
}
 
sumofsquares(array(1,2,3,4,5))</langsyntaxhighlight>
{{out}}
<pre>55</pre>
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">
(defun sum-sq (nums)
(lists:foldl
Line 885 ⟶ 1,801:
(+ acc (* x x)))
0 nums))
</syntaxhighlight>
</lang>
 
Usage:
<langsyntaxhighlight lang="lisp">
> (sum-sq '(3 1 4 1 5 9))
133
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">' [RC] Sum of Squares
 
SourceList$ ="3 1 4 1 5 9"
Line 920 ⟶ 1,836:
print "Sum of squares is "; SumOfSquares
 
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">print apply "sum map [? * ?] [1 2 3 4 5] ; 55</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">sum(List, Sum) :-
sum(List, 0, Sum).
 
Line 932 ⟶ 1,855:
sum([X| Xs], Acc, Sum) :-
Acc2 is Acc + X,
sum(Xs, Acc2, Sum).</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="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})</langsyntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="m2000 interpreter">
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
</syntaxhighlight>
 
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)
 
<syntaxhighlight lang="m2000 interpreter">
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
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
F := V -> add(v^2, v in V):
F(<1,2,3,4,5>);
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
As a function 1:
<langsyntaxhighlight lang="mathematica">SumOfSquares[x_]:=Total[x^2]
SumOfSquares[{1,2,3,4,5}]</langsyntaxhighlight>
As a function 2:
<langsyntaxhighlight lang="mathematica">SumOfSquares[x_]:=x.x
SumOfSquares[{1,2,3,4,5}]</langsyntaxhighlight>
Pure function 1: (postfix operator in the following examples)
<langsyntaxhighlight lang="mathematica">{1,2,3,4,5} // Total[#^2] &</langsyntaxhighlight>
Pure function 2:
<langsyntaxhighlight lang="mathematica">{1, 2, 3, 4, 5} // #^2 & // Total</langsyntaxhighlight>
Pure function 3:
<langsyntaxhighlight lang="mathematica">{1, 2, 3, 4, 5} // #.#&</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight Matlablang="matlab">function [squaredSum] = sumofsquares(inputVector)
squaredSum = sum( inputVector.^2 );</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">nums : [3,1,4,1,5,9];
sum(nums[i]^2,i,1,length(nums));</langsyntaxhighlight>
or
<langsyntaxhighlight lang="maxima">nums : [3,1,4,1,5,9];
lsum(el^2, el, nums);</langsyntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module sum_of_squares.
:- interface.
Line 989 ⟶ 1,974:
 
sum_of_squares(Ns) = list.foldl((func(N, Acc) = Acc + N * N), Ns, 0).
</syntaxhighlight>
</lang>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">((bool) ((dup *) (+) map-reduce) (pop 0) if) :sq-sum
 
(1 2 3 4 5) sq-sum puts
() sq-sum puts</syntaxhighlight>
{{out}}
<pre>
55
0
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="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([])</syntaxhighlight>
{{out}}
<pre>2854
55
0</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">x^2 + С/П БП 00</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE SumSquares EXPORTS Main;
 
IMPORT IO, Fmt;
Line 1,013 ⟶ 2,027:
IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0})));
IO.Put("\n");
END SumSquares.</langsyntaxhighlight>
 
=={{header|MOO}}==
<langsyntaxhighlight lang="moo">@verb #100:sum_squares this none this rd
@program #100:sum_squares
sum = 0;
Line 1,031 ⟶ 2,045:
;#100:sum_squares({})
{} => 0
</syntaxhighlight>
</lang>
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="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</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="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})</syntaxhighlight>
{{out}}
<pre>0
55
11944076</pre>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">SS(x : list[double]) : double
{
|[] => 0.0
|_ => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_)
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/*NetRexx *************************************************************
* program to sum the squares of a vector of fifteen numbers.
* translated from REXX
Line 1,065 ⟶ 2,100:
sum=sum + x**2 /*add its square to the sum. */
end
say "The sum of" n "elements for the V vector is:" sum</langsyntaxhighlight>
{{out}}
<pre>The sum of 15 elements for the V vector is: 10650.25</pre>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(apply + (map (fn(x) (* x x)) '(3 1 4 1 5 9)))
-> 133
(apply + (map (fn(x) (* x x)) '()))
-> 0</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight 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}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Sum {
Line 1,098 ⟶ 2,182:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">List.fold_left (fun sum a -> sum + a * a) 0 ints</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml">List.fold_left (fun sum a -> sum +. a *. a) 0. floats</langsyntaxhighlight>
 
=={{header|Octave}}==
 
<syntaxhighlight lang="octave">a = [1:10];
sumsq = sum(a .^ 2);</syntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">#sq [1, 1.2, 3, 4.5 ] map(#sq) sum</langsyntaxhighlight>
 
=={{header|OctaveOl}}==
<syntaxhighlight lang="scheme">
(define (sum-of-squares l)
(fold + 0 (map * l l)))
 
(print (sum-of-squares '(1 2 3 4 5 6 7 8 9 10)))
<lang octave>a = [1:10];
; ==> 385
sumsq = sum(a .^ 2);</lang>
</syntaxhighlight>
 
=={{header|Order}}==
 
<langsyntaxhighlight lang="c">#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)))
))</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {SumOfSquares Xs}
for X in Xs sum:S do
Line 1,132 ⟶ 2,225:
end
in
{Show {SumOfSquares [3 1 4 1 5 9]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
===Generic===
<lang parigp>ss(v)={
It is possible to apply a function, in this case ^2 to each element of an iterable and sum the result:
<syntaxhighlight lang="parigp">ss(v)={
sum(i=1,#v,v[i]^2)
};</langsyntaxhighlight>
===Specific===
For this particular task the product of a row matrix and its transpose is the sum of squares:
<syntaxhighlight lang="parigp">
n=[2,5,23]
print(n*n~)
n=[]
print(n*n~)
</syntaxhighlight>
{{out}}
<pre>
558
0
</pre>
 
=={{header|Pascal}}==
Line 1,143 ⟶ 2,251:
{{libheader|Math}}
Example from the documenation of the run time library:
<langsyntaxhighlight lang="pascal">Program Example45;
 
{ Program to demonstrate the SumOfSquares function. }
Line 1,161 ⟶ 2,269:
Writeln('Sum squares : ',SumOfSquares(ExArray):8:4);
Writeln('Sum squares (b) : ',SumOfSquares(@ExArray[1],100):8:4);
end.</langsyntaxhighlight>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
var vector := Arr(1,2,3,4,5,6,7);
vector.Sum(x -> x * x).Println
</syntaxhighlight>
{{out}}
<pre>
140
</pre>
 
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub sum_of_squares {
my $sum = 0;
$sum += $_**2 foreach @_;
Line 1,170 ⟶ 2,290:
}
 
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</langsyntaxhighlight>
or
<langsyntaxhighlight lang="perl">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";</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{works with|Rakudo|#21 "Seattle"}}
<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}}==
<lang perl6>say [+] map * ** 2, 3, 1, 4, 1, 5, 9;</lang>
<syntaxhighlight lang="phixmonti">0 tolist
10 for 0 put endfor
 
0 swap len for
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.
get
Another convenient way to distribute the exponentiation is via the cross metaoperator, which
2 power rot + swap
as a list infix is looser than comma in precedence but tighter than the reduction list operator:
endfor
 
drop print /# 385 #/</syntaxhighlight>
<lang perl6>say [+] 3,1,4,1,5,9 X** 2</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
function sum_squares(array $args) {
return array_reduce(
Line 1,197 ⟶ 2,327:
);
}
</syntaxhighlight>
</lang>
 
In PHP5.3 support for anonymous functions was reworked. While the above code would still work, it is suggested to use
 
<langsyntaxhighlight lang="php">
function sum_squares(array $args) {
return array_reduce($args, function($x, $y) {
Line 1,207 ⟶ 2,337:
}, 0);
}
</syntaxhighlight>
</lang>
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}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (sum '((N) (* N N)) (3 1 4 1 5 9))
-> 133
: (sum '((N) (* N N)) ())
-> 0</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
 
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}}==
<syntaxhighlight lang="plainenglish">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.</syntaxhighlight>
{{out}}
<pre>
Sum of squares: 133-61/100
</pre>
 
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">define sum_squares(v);
lvars s = 0, j;
for j from 1 to length(v) do
Line 1,233 ⟶ 2,509:
enddefine;
 
sum_squares({1 2 3 4 5}) =></langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/sqrsum{
/x exch def
Line 1,251 ⟶ 2,527:
sum ==
}def
</syntaxhighlight>
</lang>
 
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
[3 1 4 1 5 9] 0 {dup * +} fold
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function Get-SquareSum ($a) {
if ($a.Length -eq 0) {
return 0
Line 1,268 ⟶ 2,544:
return $x.Sum
}
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
sum([],0).
sum([H|T],S) :- sum(T, S1), S is S1 + (H * H).
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure SumOfSquares(List base())
ForEach base()
Sum + base()*base()
Next
ProcedureReturn Sum
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
'''Using generator expression'''
<lang python>sum(x*x for x in [1, 2, 3, 4, 5])</lang>
<syntaxhighlight lang="python">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])</syntaxhighlight>
 
'''Functional versionversions:'''
<syntaxhighlight lang="python"># using lambda and map:
<lang python>sum(map(lambda x: x*x, [1, 2, 3, 4, 5]))</lang>
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
=={{header|Prolog}}==
from itertools import repeat
sum([],0).
sum(map(pow, [H|T]1,S) :-2, sum(T3, S1)4, S is S1 +5], repeat(H * H2))).
 
# 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])</syntaxhighlight>
 
'''Using NumPy:'''
<syntaxhighlight lang="python">import numpy as np
a = np.array([1, 2, 3, 4, 5])
np.sum(a ** 2)</syntaxhighlight>
 
=={{header|Q}}==
<syntaxhighlight lang="q">ssq:{sum x*x}</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 0 swap witheach [ 2 ** + ] ] is sumofsquares ( [ --> n )</syntaxhighlight>
 
{{out}}
 
Testing in the Quackery shell.
 
<pre>> 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.</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">arr <- c(1,2,3,4,5)
result <- sum(arr^2)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(for/sum ([x #(3 1 4 1 5 9)]) (* x x))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>say [+] map * ** 2, (3, 1, 4, 1, 5, 9);</syntaxhighlight>
 
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.
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:
 
<syntaxhighlight lang="raku" line>say [+] <3 1 4 1 5 9> X** 2</syntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven">define sumOfSqrs use $lst
0 $lst each dup * +
 
[ 1 2 3 4] sumOfSqrs "Sum of squares: %d\n" print</langsyntaxhighlight>
{{out}}
<pre>Sum of squares: 30</pre>
 
=={{header|REXXRed}}==
<syntaxhighlight lang="red">Red [
<lang rexx>/*REXX program sums the squares of a vector which contains 15 numbers.*/
date: 2021-10-25
numeric digits 50 /*allow 50-digit # (default is 9)*/
red-version: 0.6.4
v=-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with some #s. */
description: "Find the sum of squares of a numeric vector"
sum=0 /*initialize SUM to zero. */
]
/*if vector is empty, sum = zero.*/
do k=1 for words(v) /*process each number in the list*/
sum=sum + word(v,k)**2 /*add squared element to the sum.*/
end /*k*/
 
sum-squares: function [
say 'The sum of ' words(v) " squared elements for the V vector is: " sum
"Returns the sum of squares of all values in a block"
/*stick a fork in it, we're done.*/
values [any-list! vector!]
/*stick a fork in it, we're done.*/</lang>
][
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}}==
===input from pgm===
<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*/
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: " $</syntaxhighlight>
'''output''' &nbsp; using an internal vector (list) of numbers:
<pre>
The sum of 15 squared elements for the V vector is: 10650.25
</pre>
 
===input from C.L.===
=={{header|Ruby}}==
<syntaxhighlight lang="rexx">/*REXX program sums the squares of the numbers in a (numeric) vector of 15 numbers. */
<lang ruby>[3,1,4,1,5,9].inject(0) { |sum,x| sum += x**2 }</lang>
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: " $</syntaxhighlight>
'''output''' &nbsp; using a vector (list) of numbers from the command line:
<pre>
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
or
</pre>
 
=={{header|Ring}}==
<lang ruby>[3,1,4,1,5,9].map { |x| x**2 }.reduce(0, :+)</lang>
<syntaxhighlight lang="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
</syntaxhighlight>
 
=={{header|RPL}}==
Zero-length vectors don't exist in RPL, so there's no need to tackle this case:
≪ 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>
{ 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}}==
<syntaxhighlight lang="ruby">[3,1,4,1,5,9].sum(0){|x| x*x}</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">list$ = "1,2,3,4,5"
print sumOfSquares(list$)
 
Line 1,340 ⟶ 2,787:
sumOfSquares = sumOfSquares + val(word$(sos$,i,","))^2
wend
END FUNCTION</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn sq_sum(v: &[f64]) -> f64 {
v.iter().fold(0., |sum, &num| sum + num*num)
}
Line 1,353 ⟶ 2,800:
let u : Vec<f64> = vec![];
println!("{}", sq_sum(&u));
}</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
 
sqsum(s, e:FLT):FLT is
Line 1,371 ⟶ 2,818:
end;
 
end;</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="scala">def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (sum-of-squares l)
(apply + (map * l l)))</langsyntaxhighlight>
 
> (sum-of-squares (list 3 1 4 1 5 9))
Line 1,386 ⟶ 2,833:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
Line 1,407 ⟶ 2,854:
writeln(squaredSum(list1));
writeln(squaredSum(list2));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func sum_of_squares(vector) {
var sum = 0;
vector.each { |n| sum += n**2 };
Line 1,417 ⟶ 2,864:
 
say sum_of_squares([]); # 0
say sum_of_squares([1,2,3]); # 14</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">{1. 2. 3} reduce: [|:x :y| y squared + x].
{} reduce: [|:x :y| y squared + x] ifEmpty: [0].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared]</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 1,433 ⟶ 2,880:
{{works with|CSnobol}}
 
<langsyntaxhighlight SNOBOL4lang="snobol4"> define('ssq(a)i') :(ssq_end)
ssq i = i + 1; ssq = ssq + (a<i> * a<i>) :s(sumsq)f(return)
ssq_end
Line 1,441 ⟶ 2,888:
loop i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
output = str ' -> ' sumsq(a)
end</langsyntaxhighlight>
 
{{out}}
<pre> 1 2 3 5 7 11 13 17 19 23 -> 1557</pre>
 
=={{header|SQL}}==
 
<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>.
 
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">foldl (fn (a, sum) => sum + a * a) 0 ints</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sml">foldl (fn (a, sum) => sum + a * a) 0.0 reals</langsyntaxhighlight>
 
=={{header|SQLStata}}==
=== Mata ===
<syntaxhighlight lang="stata">a = 1..100
sum(a:^2)
338350
 
a = J(0, 1, .)
<lang sql>select sum(x*x) from vector</lang>
length(a)
 
0
Note that this assumes that the values in our vector are named <code>x</code>.
sum(a:^2)
0</syntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func sumSq(s: [Int]) -> Int {
return s.map{$0 * $0}.reduce(0, +)
}</langsyntaxhighlight>
 
=={{header|TclTailspin}}==
<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
 
# {*} 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_ofputs {x[sum_of_squares {*}]; $x $x}} {1 2 3 4 5} ;# ==> 55</lang>0
</syntaxhighlight>
 
=={{header|Trith}}==
<langsyntaxhighlight lang="trith">[3 1 4 1 5 9] 0 [dup * +] foldl</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
array="3'1'4'1'5'9",sum=0
Line 1,507 ⟶ 2,957:
ENDLOOP
PRINT sum
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,515 ⟶ 2,965:
=={{header|UnixPipes}}==
 
<langsyntaxhighlight lang="bash">folder() {
(read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res)
}
Line 1,526 ⟶ 2,976:
 
 
(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang="sh">sum_squares () {
_r=0
for _n
do
: "$((_r += _n * _n))"
done
echo "$_r"
}
 
sum_squares 3 1 4 1 5 9</syntaxhighlight>
{{out}}
<pre>133</pre>
 
=={{header|Ursala}}==
Line 1,533 ⟶ 2,997:
maps the product function to all pairs, and then sums the
result by way of the reduction operator, -:.
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
ssq = sum:-0+ product*iip
Line 1,539 ⟶ 3,003:
#cast %n
 
main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93></langsyntaxhighlight>
{{out}}
<pre>62223</pre>
 
=={{header|V}}==
<langsyntaxhighlight lang="v">[sumsq [dup *] map 0 [+] fold].
 
[] sumsq
=0
[1 2 3] sumsq</langsyntaxhighlight>
=14
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public Sub sum_of_squares()
Debug.Print WorksheetFunction.SumSq([{1,2,3,4,5,6,7,8,9,10}])
End Sub</syntaxhighlight>{{out}}
<pre> 385 </pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
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())
</syntaxhighlight>
 
{{Out}}
<pre>
55
0
</pre>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">
Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer
If i Is Nothing OrElse i.Count = 0 Then
Line 1,589 ⟶ 3,080:
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,610 ⟶ 3,101:
SumOfSquares(15) = 1240
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>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@sum !*^@sq [3 1 4 1 5 9] ; returns 133</langsyntaxhighlight>
<langsyntaxhighlight lang="wortel">@sum !*^@sq [] ; returns 0</langsyntaxhighlight>
As a function:
<syntaxhighlight lang ="wortel">^(@sum *^@sq)</langsyntaxhighlight>
Iterative function:
<langsyntaxhighlight lang="wortel">&a [@var sum 0 @for x of a :!+sum *x x sum]</langsyntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="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))")</syntaxhighlight>
 
{{out}}
<pre>
Vector : [1, 2, 3, -1, -2, -3]
Sum of squares : 28
</pre>
 
=={{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>.
<syntaxhighlight lang="lisp">(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)))</syntaxhighlight>
{{out}}
<pre>(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)</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func SumSq(V, L);
Line 1,633 ⟶ 3,181:
[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
]</langsyntaxhighlight>
 
{{out}}
Line 1,642 ⟶ 3,190:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">T(3,1,4,1,5,9).reduce(fcn(p,n){ p + n*n },0) //-->550
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.055</langsyntaxhighlight>