Scalar multiplication (Haskell)

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



c * \overrightarrow{u}
=
c
*
\begin{bmatrix} 
u_1 & u_2 & ... & u_n
\end{bmatrix}
=
\begin{bmatrix} 
c * u_1 & c * u_2 & ... & c * u_n
\end{bmatrix}


c * A_{m,n} 
=
c
*
\begin{bmatrix}
  a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
  a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  a_{m,1} & a_{m,2} & \cdots & a_{m,n}
\end{bmatrix}
=
\begin{bmatrix}
  c * a_{1,1} & c * a_{1,2} & \cdots & c * a_{1,n} \\
  c * a_{2,1} & c * a_{2,2} & \cdots & c * a_{2,n} \\
  \vdots  & \vdots  & \ddots & \vdots  \\
  c * a_{m,1} & c * a_{m,2} & \cdots & c * a_{m,n}
\end{bmatrix}


Contents

[edit] Scalar multiplication over vectors

[edit] Recursion

<<scale_vector_recursion.hs>>=
vscale :: (Num a) => a -> [a] -> [a]
vscale x [] = []
vscale x (u:us) = x * u : vscale x us

[edit] List Comprehension

<<scale_vector_list_comprehension.hs>>=
vscale :: (Num a) => a -> [a] -> [a]
vscale x us = [ x * u | u <- us ]

[edit] Higher Order

<<scale_vector_higher_order.hs>>=
vscale :: (Num a) => a -> [a] -> [a]
vscale x us = map (x*) us

[edit] Scalar multiplication over matrices

[edit] Recursion

<<scale_matrix_recursion_with_vscale.hs>>=
mscale :: (Num a) => a -> [[a]] -> [[a]]
mscale x [] = []
mscale x (us:uss) = vscale x us : mscale x uss

[edit] List Comprehension

<<scale_matrix_list_comprehension.hs>>=
mscale :: (Num a) => a -> [[a]] -> [[a]]
mscale x uss = [ [ x * u | u <- us ] | us <- uss ]
<<scale_matrix_list_comprehension_with_vscale.hs>>=
mscale :: (Num a) => a -> [[a]] -> [[a]]
mscale x uss = [ vscale x us | us <- uss ]

[edit] Higher Order

<<scale_matrix_higher_order.hs>>=
mscale :: (Num a) => a -> [[a]] -> [[a]]
mscale x uss = map (\us -> map (x*) us) uss
<<scale_matrix_higher_order_with_vscale.hs>>=
mscale :: (Num a) => a -> [[a]] -> [[a]]
mscale x uss = map (vscale x) uss
Download code
hijacker
hijacker
hijacker
hijacker