Adding vectors (Haskell)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Haskell | Python

Vector addition


\overrightarrow{u} + \overrightarrow{v}
=
\begin{bmatrix} 
u_1 & u_2 & ... & u_n
\end{bmatrix}
+
\begin{bmatrix} 
v_1 & v_2 & ... & v_n
\end{bmatrix}
=
\begin{bmatrix} 
u_1 + v_1 & u_2 + v_2 & ... & u_n + v_n
\end{bmatrix}

[edit] Recursion

<<vector_addition_recursive.hs>>=
vadd :: (Num a) => [a] -> [a] -> [a]
vadd [] [] = []
vadd (u:us) (v:vs) = u + v : vadd us vs

[edit] List Comprehension

<<vector_addition_list_comprehension.hs>>=
vadd :: (Num a) => [a] -> [a] -> [a]
vadd us vs = [ x + y | (x,y) <- (zip us vs) ]

[edit] Higher order

<<vector_addition_higher_order_map2.hs>>=
vadd :: (Num a) => [a] -> [a] -> [a]
vadd us vs = zipWith (+) us vs
Download code
hijacker
hijacker
hijacker
hijacker