Sum of squares: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|Ruby}}: Removed inject method, sum now more idiomatic.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 12:
=={{header|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>
Line 24:
=={{header|11l}}==
<
{{out}}
Line 32:
=={{header|360 Assembly}}==
<
SUMOFSQR CSECT
USING SUMOFSQR,R12
Line 55:
N DC AL2((PG-A)/4)
YREGS
END SUMOFSQR</
{{out}}
<pre>
Line 63:
=={{header|8086 Assembly}}==
<
cpu 8086
bits 16
Line 117:
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</
=={{header|ACL2}}==
<
(if (endp xs)
0
(+ (* (first xs) (first xs))
(sum-of-squares (rest xs)))))</
=={{header|Action!}}==
<
BYTE i
CARD res
Line 169:
Test(c,1)
Test(c,0)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sum_of_squares.png Screenshot from Atari 8-bit computer]
Line 183:
=={{header|ActionScript}}==
<
{
var sum:Number = 0;
Line 189:
sum += vector[i]*vector[i];
return sum;
}</
=={{header|Ada}}==
<
procedure Test_Sum_Of_Squares is
Line 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;</
{{out}}
<pre>
Line 217:
=={{header|Aime}}==
<
squaredsum(list l)
{
Line 244:
0;
}</
{{out}}
<pre>14
Line 258:
The computation can be written as a loop.
<
REAL sum := 0;
FOR i FROM LWB argv TO UPB argv DO
Line 267:
test:(
printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9))));
)</
{{out}}
<pre>
Line 275:
{{trans|python}}
<
PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL:
Line 290:
sum := 0;
printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data ))
)</
{{out}}
<pre>
Line 302:
{{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.
<
# -*- coding: utf-8 -*- #
Line 345:
printf(($"SUMSQ GEN: "g(0)l$, SUMSQ GEN data));
printf(($"sq SUMMAP GEN: "g(0)l$, ((REAL x)REAL: x*x)SUMMAP GEN data))
)</
{{out}}
<pre>
Line 357:
=={{header|ALGOL W}}==
<
% procedure to sum the elements of a vector. As the procedure can't find %
% the bounds of the array for itself, we pass them in lb and ub %
Line 376:
r_format := "A"; r_w := 10; r_d := 1; % set fixed point output %
write( sumSquares( numbers, 1, 5 ) );
end.</
=={{header|Alore}}==
<
var sum = 0
for i in a
Line 389:
WriteLn(sum_squares([3,1,4,1,5,9]))
end</
=={{header|APL}}==
<
square_sum 1 2 3 4 5
55
square_sum ⍬ ⍝The empty vector
0</
=={{header|AppleScript}}==
Two ways of composing a sumOfSquares function:
<
-- sumOfSquares :: Num a => [a] -> a
Line 487:
foldl(add, 0, xs)
end sum</
{{Out}}
<syntaxhighlight lang
=={{header|Arturo}}==
<
print sum map arr [x][x^2]</
{{out}}
Line 501:
=={{header|Astro}}==
<
=={{header|Asymptote}}==
<
int[] a={1, 2, 3, 4, 5, 6};
Line 510:
suma = suma + a[i] ^ 2;
write("The sum of squares is: ", suma);</
=={{header|AutoHotkey}}==
<
Loop, Parse, list, %A_Space%
sum += A_LoopField**2
MsgBox,% sum</
=={{header|AWK}}==
Vectors are read, space-separated, from stdin; sum of squares goes to stdout. The empty line produces 0.
<
3 1 4 1 5 9
133
0</
=={{header|BASIC}}==
{{works with|QBasic}}
Assume the numbers are in an array called <code>a</code>.
<
FOR I = LBOUND(a) TO UBOUND(a)
sum = sum + a(I) ^ 2
NEXT I
PRINT "The sum of squares is: " + sum</
==={{header|BaCon}}===
<
FUNCTION ss(int arr[], NUMBER elem)
sum = 0
Line 557:
vector[i] = i + 1
NEXT
PRINT ss(vector, elem)</
{{out}}
Line 566:
==={{header|BASIC256}}===
<
dim a(6)
Line 581:
next i
print "The sum of squares is: "; sum
end</
==={{header|BBC BASIC}}===
BBC BASIC cannot have a zero-length array.
<
vector() = 1, 2, 3, 4, 5, 6
PRINT "Sum of squares = " ; MOD(vector()) ^ 2</
{{out}}
<pre>Sum of squares = 91</pre>
==={{header|IS-BASIC}}===
<
110 NUMERIC A(1 TO N)
120 FOR I=1 TO N
Line 605:
200 NEXT
210 LET SQ=S
220 END DEF</
==={{header|Yabasic}}===
<
dim a(5)
sum = 0
Line 617:
next i
print "The sum of squares is: ", sum
end</
=={{header|bc}}==
<
auto i, s
Line 628:
return(s)
}</
=={{header|BCPL}}==
<
let sumsquares(v, len) =
Line 640:
$( let vector = table 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
writef("%N*N", sumsquares(vector, 10))
$)</
{{out}}
<pre>385</pre>
Line 646:
=={{header|BQN}}==
Similar to the BQN entry in [[Sum of a series]].
<
•Show SSq 1‿2‿3‿4‿5
•Show SSq ⟨⟩</
<syntaxhighlight lang="text">55
0</
=={{header|Bracmat}}==
<
= sum component
. 0:?sum
Line 665:
& out$(sumOfSquares$(3 4 i*5))
& out$(sumOfSquares$(a b c))
);</
{{out}}
<pre>25
Line 672:
=={{header|Brat}}==
<
=={{header|C}}==
<
double squaredsum(double *l, int e)
Line 694:
printf("%lf\n", squaredsum(NULL, 0));
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 714:
Console.WriteLine(SumOfSquares(new int[] { })); // 0
}
}</
=={{header|C++}}==
===Using accumulate===
<
#include <numeric>
#include <vector>
Line 743:
std::cout << vec_add_squares(v) << std::endl;
return 0;
}</
===Using inner_product===
<
#include <numeric>
#include <vector>
Line 760:
std::cout << std::inner_product(begin(v), end(v), begin(v), 0.0) << std::endl;
return 0;
}</
===Using Boost.Lambda===
{{libheader|Boost.Lambda}}
<
#include <vector>
#include "boost/lambda/lambda.hpp"
Line 773:
return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2);
}</
=={{header|Chef}}==
<
First input is length of vector, then rest of input is vector.
Line 798:
Serves 1.
</syntaxhighlight>
=={{header|Clojure}}==
<
(reduce #(+ %1 (* %2 %2)) 0 v))</
=={{header|CLU}}==
<
sum: int := 0
for n: int in sequence[int]$elements(ns) do
Line 819:
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</
{{out}}
<pre>0
Line 826:
=={{header|CoffeeScript}}==
<
sumOfSquares = ( list ) ->
list.reduce (( sum, x ) -> sum + ( x * x )), 0
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(loop for x across vector sum (expt x 2)))</
=={{header|Cowgol}}==
<
include "argv.coh";
Line 873:
# Print sum of squares of numbers
print_i32(sumsquare(&nums[0], len as intptr));
print_nl();</
{{out}}
Line 886:
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
def sum_squares(a)
a.map{|e| e*e}.sum()
Line 893:
puts sum_squares([1, 2, 3])
# => 14
</syntaxhighlight>
=={{header|D}}==
===Iterative Version===
<
T sum = 0;
foreach (e; a)
Line 908:
[3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln;
}</
{{out}}
<pre>133.61</pre>
===Polymorphic Functional Style===
<
auto sumSquares(Range)(Range data) pure nothrow @safe @nogc {
Line 923:
items.sumSquares.writeln;
10.iota.sumSquares.writeln;
}</
{{out}}
<pre>133.61
Line 930:
=={{header|Dart}}==
===Iterative Version===
<
var sum=0;
list.forEach((var n) { sum+=(n*n); });
Line 940:
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
}</
{{out}}
<pre>0
Line 947:
===Functional Style Version===
<
.fold(0, (num p,num n)=> p + n);
Line 954:
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
}</
{{out}}
<pre>0
Line 962:
=={{header|Delphi}}==
Delphi has standard SumOfSquares function in Math unit:
<
{$APPTYPE CONSOLE}
Line 982:
Writeln(SumOfSquares(A):6:2); // 30.00
Readln;
end.</
=={{header|Draco}}==
<
ulong sum, item;
word i, len;
Line 1,007:
writeln(sum_squares(A1(42)));
writeln(sum_squares(A5(1,2,3,4,5)))
corp</
{{out}}
<pre>0
Line 1,015:
=={{header|E}}==
<
var sum := 0
for x in numbers {
Line 1,021:
}
return sum
}</
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,057:
end
</syntaxhighlight>
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
Line 1,073:
.printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5}))
.printLine(SumOfSquares(Array.MinValue))
}</
{{out}}
<pre>
Line 1,082:
=={{header|Elixir}}==
<
133</
=={{header|Emacs Lisp}}==
<
(apply #'+ (mapcar (lambda (k) (* k k)) numbers)))
(sum-of-squares (number-sequence 0 3)) ;=> 14</
=={{header|Erlang}}==
<
=={{header|Euphoria}}==
<
atom sum
sum = 0
Line 1,102:
end for
return sum
end function</
=={{header|Excel}}==
To find the sum of squares of values from A1 to A10, type in any other cell :
<syntaxhighlight lang="excel">
=SUMSQ(A1:A10)
</syntaxhighlight>
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>
=={{header|F_Sharp|F#}}==
<
[|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 0</
=={{header|Factor}}==
<
: sum-of-squares ( seq -- n ) [ sq ] map-sum ;
{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares</
=={{header|FALSE}}==
<syntaxhighlight lang="false">
0 3 1 4 1 5 9$*\ [$0=~][$*+\]#%.
</syntaxhighlight>
=={{header|Fantom}}==
<
class SumSquares
{
Line 1,154:
}
}
</syntaxhighlight>
=={{header|Fish}}==
<syntaxhighlight lang="fish">v
\0&
>l?!v:*&+&
>&n;</
=={{header|Forth}}==
<
0e
dup 0= if 2drop exit then
Line 1,171:
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fsum**2 f. \ 133.</
=={{header|Fortran}}==
In ISO Fortran 90 orlater, use SUM intrinsic and implicit element-wise array arithmetic:
<
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real :: result, zresult
Line 1,183:
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</
=={{header|FreeBASIC}}==
<
Function SumSquares(a() As Double) As Double
Line 1,203:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,211:
=={{header|Frink}}==
<
f = {|x| x^2} // Anonymous function which squares its argument
a = [1,2,3,5,7]
println[sum[map[f,a], 0]]
</syntaxhighlight>
=={{header|Fōrmulæ}}==
Line 1,226:
=={{header|GAP}}==
<
# It's necessary to check for the empty vector though
SumSq := function(v)
Line 1,234:
return v*v;
fi;
end;</
=={{header|GEORGE}}==
<
0
1, n rep (i)
read print dup mult +
]
print</
data
<pre>
Line 1,277:
=={{header|Go}}==
;Implementation
<
import "fmt"
Line 1,289:
}
fmt.Println(sum)
}</
{{out}}
<pre>
Line 1,295:
</pre>
;Library
<
import (
Line 1,307:
func main() {
fmt.Println(floats.Dot(v, v))
}</
{{out}}
<pre>
Line 1,314:
=={{header|Golfscript}}==
<
# usage example
[1 2 3]sqsum puts</
=={{header|Groovy}}==
<
// square via multiplication
Line 1,328:
sumSq = array.collect { it ** 2 }.sum()
println sumSq</
{{out}}
Line 1,336:
=={{header|Haskell}}==
Three approaches:
<
versions =
[ sum . fmap (^ 2) -- ver 1
Line 1,345:
main :: IO ()
main =
mapM_ print ((`fmap` [[3, 1, 4, 1, 5, 9], [1 .. 6], [], [1]]) <$> versions)</
{{Out}}
<pre>[133,91,0,1]
Line 1,352:
=={{header|Icon}} and {{header|Unicon}}==
<
local lst
lst := []
Line 1,365:
every total +:= !lst ^ 2
return total
end</
=={{header|IDL}}==
<syntaxhighlight lang
=={{header|Inform 7}}==
<
To decide which number is the sum of (N - number) and (M - number) (this is summing):
Line 1,387:
say line break;
say the sum of squares of {1, 2, 3};
end the story.</
=={{header|Io}}==
<
=={{header|J}}==
<
That is, sum composed with square. The verb also works on higher-ranked arrays. For example:
<
133
ss $0 NB. $0 is a zero-length vector
Line 1,404:
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.
<
z=. 0
for_i. i.#y do. z=. z+*:i{y end.
Line 1,419:
0
ss1 x
9.09516 5.19512 5.84173 6.6916</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
{
public static void main(final String[] args)
Line 1,433:
System.out.println("The sum of the squares is: " + sum);
}
}</
=={{header|JavaScript}}==
===ES5===
<
var sum = 0;
var i, iLen;
Line 1,447:
}
alert(sumsq([1,2,3,4,5])); // 55</
An alternative using a while loop and Math.pow
<
var sum = 0,
i = array.length;
Line 1,460:
}
alert(sumsq([1,2,3,4,5])); // 55</
{{libheader|Functional}}<
map (JS 1.6) and reduce (JS 1.8)
<
===ES6===
Two ways of composing a sumOfSquares function
<
'use strict';
Line 1,506:
// MAIN ---
return main();
})();</
{{Out}}
<pre>133
Line 1,513:
=={{header|jq}}==
jq supports both arrays and streams, and so we illustrate how to handle both.
<
def ss: map(.*.) | add;
# ss for a stream, S, without creating an intermediate array:
def ss(S): reduce S as $x (0; . + ($x * $x) );</
# SIGMA(exp) computes the sum of exp over the input array:
def SIGMA(exp): map(exp) | add;
Line 1,523:
# 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;
</syntaxhighlight>
Demonstration:<
"ss: \( [range(0;n)] | ss )",
"ss(S): \( ss( range(0;n) ) )",
Line 1,538:
;
demo(3) # 0^2 + 1^2 + 2^2</
{{out}}
<
"ss(S): 5"
"SIGMA(.*.): 5"
"SIGMA(.*.;S): 5"
"mapreduce(.*.; add; 0): 5"</
=={{header|Julia}}==
There are several easy ways to do this in Julia:
<
55
Line 1,558:
julia> sum([x^2 for x in []])
0</
=={{header|K}}==
<syntaxhighlight lang="k">
ss: {+/x*x}
ss 1 2 3 4 5
Line 1,567:
ss@!0
0
</syntaxhighlight>
=={{header|Kotlin}}==
Line 1,578:
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.
<
import kotlin.system.measureTimeMillis
import kotlin.time.milliseconds
Line 1,629:
for (v in longArray) acc += v
}
}</
{{out}}
Line 1,656:
=={{header|Lambdatalk}}==
<
{def sumsq
{lambda {:s}
Line 1,666:
{sumsq 0}
-> 0
</syntaxhighlight>
=={{header|Lang5}}==
<
=={{header|Lasso}}==
<
local(sum = 0)
Line 1,683:
}
sumofsquares(array(1,2,3,4,5))</
{{out}}
<pre>55</pre>
=={{header|LFE}}==
<
(defun sum-sq (nums)
(lists:foldl
Line 1,694:
(+ acc (* x x)))
0 nums))
</syntaxhighlight>
Usage:
<
> (sum-sq '(3 1 4 1 5 9))
133
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
SourceList$ ="3 1 4 1 5 9"
Line 1,729:
print "Sum of squares is "; SumOfSquares
end</
=={{header|LiveCode}}==
<
repeat for each item n in nums
add (n * n) to m
end repeat
put m // 55</
=={{header|Logo}}==
<
=={{header|Logtalk}}==
<
sum(List, 0, Sum).
Line 1,748:
sum([X| Xs], Acc, Sum) :-
Acc2 is Acc + X,
sum(Xs, Acc2, Sum).</
=={{header|Lua}}==
<
function squaresumt(t) return squaresum(unpack(t)) end
print(squaresumt{3, 5, 4, 1, 7})</
=={{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
Line 1,786:
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 })
Line 1,794:
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)
Line 1,816:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang="maple">
F := V -> add(v^2, v in V):
F(<1,2,3,4,5>);
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
As a function 1:
<
SumOfSquares[{1,2,3,4,5}]</
As a function 2:
<
SumOfSquares[{1,2,3,4,5}]</
Pure function 1: (postfix operator in the following examples)
<
Pure function 2:
<
Pure function 3:
<
=={{header|MATLAB}}==
<
squaredSum = sum( inputVector.^2 );</
=={{header|Maxima}}==
<
sum(nums[i]^2,i,1,length(nums));</
or
<
lsum(el^2, el, nums);</
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module sum_of_squares.
:- interface.
Line 1,867:
sum_of_squares(Ns) = list.foldl((func(N, Acc) = Acc + N * N), Ns, 0).
</syntaxhighlight>
=={{header|min}}==
{{works with|min|0.19.3}}
<
(1 2 3 4 5) sq-sum puts
() sq-sum puts</
{{out}}
<pre>
Line 1,882:
=={{header|MiniScript}}==
<
sum = 0
for item in seq
Line 1,892:
print sumOfSquares([4, 8, 15, 16, 23, 42])
print sumOfSquares([1, 2, 3, 4, 5])
print sumOfSquares([])</
{{out}}
<pre>2854
Line 1,899:
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">x^2 + С/П БП 00</
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 1,920:
IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0})));
IO.Put("\n");
END SumSquares.</
=={{header|MOO}}==
<
@program #100:sum_squares
sum = 0;
Line 1,938:
;#100:sum_squares({})
{} => 0
</syntaxhighlight>
=={{header|MUMPS}}==
<
;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</
=={{header|Nanoquery}}==
<
if len(vector) = 0
return 0
Line 1,963:
println sum_squares({})
println sum_squares({1, 2, 3, 4, 5})
println sum_squares({10, 3456, 2, 6})</
{{out}}
<pre>0
Line 1,970:
=={{header|Nemerle}}==
<
{
|[] => 0.0
|_ => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_)
}</
=={{header|NetRexx}}==
<
* program to sum the squares of a vector of fifteen numbers.
* translated from REXX
Line 1,993:
sum=sum + x**2 /*add its square to the sum. */
end
say "The sum of" n "elements for the V vector is:" sum</
{{out}}
<pre>The sum of 15 elements for the V vector is: 10650.25</pre>
=={{header|NewLISP}}==
<
-> 133
(apply + (map (fn(x) (* x x)) '()))
-> 0</
=={{header|Nim}}==
<
proc sumSquares[T: SomeNumber](a: openArray[T]): T =
Line 2,013:
let a2: seq[float] = @[]
echo a2, " → ", sumSquares(a2)</
{{out}}
Line 2,020:
=={{header|Objeck}}==
<
bundle Default {
class Sum {
Line 2,037:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
<
=={{header|Octave}}==
<
sumsq = sum(a .^ 2);</
=={{header|Oforth}}==
<
=={{header|Ol}}==
<
(define (sum-of-squares l)
(fold + 0 (map * l l)))
Line 2,061:
(print (sum-of-squares '(1 2 3 4 5 6 7 8 9 10)))
; ==> 385
</syntaxhighlight>
=={{header|Order}}==
<
ORDER_PP(8to_lit(
8seq_fold(8plus, 0,
8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(3, 1, 4, 1, 5, 9)))
))</
=={{header|Oz}}==
<
fun {SumOfSquares Xs}
for X in Xs sum:S do
Line 2,080:
end
in
{Show {SumOfSquares [3 1 4 1 5 9]}}</
=={{header|PARI/GP}}==
===Generic===
It is possible to apply a function, in this case ^2 to each element of an iterable and sum the result:
<
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~)
</syntaxhighlight>
{{out}}
<pre>
Line 2,106:
{{libheader|Math}}
Example from the documenation of the run time library:
<
{ Program to demonstrate the SumOfSquares function. }
Line 2,124:
Writeln('Sum squares : ',SumOfSquares(ExArray):8:4);
Writeln('Sum squares (b) : ',SumOfSquares(@ExArray[1],100):8:4);
end.</
=={{header|Perl}}==
<
my $sum = 0;
$sum += $_**2 foreach @_;
Line 2,133:
}
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</
or
<
sub sum_of_squares {
reduce { $a + $b **2 } 0, @_;
}
print sum_of_squares(3, 1, 4, 1, 5, 9), "\n";</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,153:
=={{header|Phixmonti}}==
<
10 for 0 put endfor
Line 2,161:
endfor
drop print /# 385 #/</
=={{header|PHP}}==
<
function sum_squares(array $args) {
return array_reduce(
Line 2,170:
);
}
</syntaxhighlight>
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) {
Line 2,180:
}, 0);
}
</syntaxhighlight>
Usage for both examples: <code>sum_squares(array(1,2,3,4,5)); // 55</code>
=={{header|Picat}}==
<
List = 1..666,
println(sum_squares(List)),
Line 2,191:
sum_squares([]) = 0.
sum_squares(List) = sum([I*I : I in List]).</
{{out}}
Line 2,198:
=={{header|PicoLisp}}==
<
-> 133
: (sum '((N) (* N N)) ())
-> 0</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
put (sum(A**2));
</syntaxhighlight>
=={{header|Plain English}}==
<
Start up.
Create a list.
Line 2,244:
Add the element's ratio times the element's ratio to the ratio.
Put the element's next into the element.
Repeat.</
{{out}}
<pre>
Line 2,252:
=={{header|Pop11}}==
<
lvars s = 0, j;
for j from 1 to length(v) do
Line 2,260:
enddefine;
sum_squares({1 2 3 4 5}) =></
=={{header|PostScript}}==
<syntaxhighlight lang="text">
/sqrsum{
/x exch def
Line 2,278:
sum ==
}def
</syntaxhighlight>
{{libheader|initlib}}
<
[3 1 4 1 5 9] 0 {dup * +} fold
</syntaxhighlight>
=={{header|PowerShell}}==
<
if ($a.Length -eq 0) {
return 0
Line 2,295:
return $x.Sum
}
}</
=={{header|Prolog}}==
Line 2,302:
=={{header|PureBasic}}==
<
ForEach base()
Sum + base()*base()
Next
ProcedureReturn Sum
EndProcedure</
=={{header|Python}}==
'''Using generator expression'''
<
# 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:'''
<
sum(map(lambda x: x * x, [1, 2, 3, 4, 5]))
# or
Line 2,344:
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:'''
<
a = np.array([1, 2, 3, 4, 5])
np.sum(a ** 2)</
=={{header|Q}}==
<syntaxhighlight lang
=={{header|Quackery}}==
<
{{out}}
Line 2,379:
=={{header|R}}==
<
result <- sum(arr^2)</
=={{header|Racket}}==
<
#lang racket
(for/sum ([x #(3 1 4 1 5 9)]) (* x x))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
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,396:
as a list infix is looser than comma in precedence but tighter than the reduction list operator:
<syntaxhighlight lang="raku"
=={{header|Raven}}==
<
0 $lst each dup * +
[ 1 2 3 4] sumOfSqrs "Sum of squares: %d\n" print</
{{out}}
<pre>Sum of squares: 30</pre>
=={{header|Red}}==
<
date: 2021-10-25
red-version: 0.6.4
Line 2,423:
print sum-squares []
print sum-squares [1 2 0.5]</
{{out}}
<pre>
Line 2,432:
=={{header|ReScript}}==
With integers:
<
Js.log(Js.Array2.reduce([10, 2, 4], sumOfSquares, 0))</
With floats:
<
Js.log(Js.Array2.reduce([10., 2., 4.], sumOfSquares, 0.))</
=={{header|REXX}}==
===input from pgm===
<
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.*/
Line 2,452:
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:
<pre>
Line 2,459:
===input from C.L.===
<
numeric digits 100 /*allow 100─digit numbers; default is 9*/
parse arg v /*get optional numbers from the C.L. */
Line 2,470:
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:
<pre>
Line 2,479:
=={{header|Ring}}==
<
aList = [1,2,3,4,5]
see sumOfSquares(aList)
Line 2,489:
next
return sumOfSquares
</syntaxhighlight>
=={{header|Ruby}}==
<
=={{header|Run BASIC}}==
<
print sumOfSquares(list$)
Line 2,503:
sumOfSquares = sumOfSquares + val(word$(sos$,i,","))^2
wend
END FUNCTION</
=={{header|Rust}}==
<
v.iter().fold(0., |sum, &num| sum + num*num)
}
Line 2,516:
let u : Vec<f64> = vec![];
println!("{}", sq_sum(&u));
}</
=={{header|Sather}}==
<
sqsum(s, e:FLT):FLT is
Line 2,534:
end;
end;</
=={{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.
<
=={{header|Scheme}}==
<
(apply + (map * l l)))</
> (sum-of-squares (list 3 1 4 1 5 9))
Line 2,549:
=={{header|Seed7}}==
<
include "float.s7i";
Line 2,570:
writeln(squaredSum(list1));
writeln(squaredSum(list2));
end func;</
=={{header|Sidef}}==
<
var sum = 0;
vector.each { |n| sum += n**2 };
Line 2,580:
say sum_of_squares([]); # 0
say sum_of_squares([1,2,3]); # 14</
=={{header|Slate}}==
<
{} reduce: [|:x :y| y squared + x] ifEmpty: [0].</
=={{header|Smalltalk}}==
<
=={{header|SNOBOL4}}==
Line 2,596:
{{works with|CSnobol}}
<
ssq i = i + 1; ssq = ssq + (a<i> * a<i>) :s(sumsq)f(return)
ssq_end
Line 2,604:
loop i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
output = str ' -> ' sumsq(a)
end</
{{out}}
Line 2,611:
=={{header|SQL}}==
<
Note that this assumes that the values in our vector are named <code>x</code>.
Line 2,617:
=={{header|Standard ML}}==
<
<
=={{header|Stata}}==
=== Mata ===
<
sum(a:^2)
338350
Line 2,631:
0
sum(a:^2)
0</
=={{header|Swift}}==
<
return s.map{$0 * $0}.reduce(0, +)
}</
=={{header|Tailspin}}==
<
templates ssq
when <[](0)> do 0 !
Line 2,648:
[] -> ssq -> !OUT::write // outputs 0
[1..5] -> ssq -> !OUT::write // outputs 55
</syntaxhighlight>
=={{header|Tcl}}==
<
namespace path ::tcl::mathop
Line 2,660:
puts [sum_of_squares {1 2 3 4}]; # ==> 30
puts [sum_of_squares {}]; # ==> 0
</syntaxhighlight>
=={{header|Trith}}==
<
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
array="3'1'4'1'5'9",sum=0
Line 2,673:
ENDLOOP
PRINT sum
</syntaxhighlight>
{{out}}
<pre>
Line 2,681:
=={{header|UnixPipes}}==
<
(read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res)
}
Line 2,692:
(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold</
=={{header|Unix shell}}==
<
1
2
Line 2,705:
$ cat toto toto | paste -sd* | bc -l
1048576
</syntaxhighlight>
=={{header|Ursala}}==
Line 2,712:
maps the product function to all pairs, and then sums the
result by way of the reduction operator, -:.
<
ssq = sum:-0+ product*iip
Line 2,718:
#cast %n
main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93></
{{out}}
<pre>62223</pre>
=={{header|V}}==
<
[] sumsq
=0
[1 2 3] sumsq</
=14
=={{header|VBA}}==
<
Debug.Print WorksheetFunction.SumSq([{1,2,3,4,5,6,7,8,9,10}])
End Sub</
<pre> 385 </pre>
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function sum_of_squares(arr)
If UBound(arr) = -1 Then
Line 2,749:
WScript.StdOut.WriteLine sum_of_squares(Array(1,2,3,4,5))
WScript.StdOut.WriteLine sum_of_squares(Array())
</syntaxhighlight>
{{Out}}
Line 2,758:
=={{header|Visual Basic .NET}}==
<
Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer
If i Is Nothing OrElse i.Count = 0 Then
Line 2,795:
End Function
</syntaxhighlight>
{{out}}
<pre>
Line 2,819:
=={{header|Wortel}}==
<
<
As a function:
<syntaxhighlight lang
Iterative function:
<
=={{header|Wren}}==
<
var v = [1, 2, 3, -1, -2, -3]
System.print("Vector : %(v)")
System.print("Sum of squares : %(sumSquares.call(v))")</
{{out}}
Line 2,841:
=={{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>.
<
(defun sumsq (xs)
(if (null xs)
Line 2,854:
(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)))</
{{out}}
<pre>(THE SUM OF THE SQUARES OF THE FIRST SEVEN PRIME NUMBERS IS 666)
Line 2,860:
=={{header|XPL0}}==
<
func SumSq(V, L);
Line 2,872:
[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
]</
{{out}}
Line 2,881:
=={{header|zkl}}==
<
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</
|