Dot product

From Rosetta Code
Revision as of 07:57, 24 February 2010 by rosettacode>Spoon! (added haskell)
Task
Dot product
You are encouraged to solve this task according to the task description, using any language you may know.

Create a function/use an in-built function, to compute the dot product, also known as the scaler product of two vectors.
If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors [1, 3, -5] and [4, -2, -1].

To calculate the dot product of two vectors, each vector must be the same length; multiply corresponding terms from each vector then sum the results to produce the answer:

Haskell

<lang haskell>dotp a b | length a == length b = sum (zipWith (*) a b)

        | otherwise = error "Vector sizes must match"

main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3</lang>

Python

<lang python>def dotp(a,b):

   assert len(a) == len(b), 'Vector sizes must match'
   return sum(aterm * bterm for aterm,bterm in zip(a, b))

if __name__ == '__main__':

   a, b = [1, 3, -5], [4, -2, -1]
   dotp(a,b)
   assert dotp(a,b) == 3</lang>