-
- As an example of a common hardware design where the use of higher-order
- functions leads to a very natural description is a FIR filter, which is
- basically the dot-product of two vectors:
-
- \begin{equation}
- y_t = \sum\nolimits_{i = 0}^{n - 1} {x_{t - i} \cdot h_i }
- \end{equation}
-
- A FIR filter multiplies fixed constants ($h$) with the current
- and a few previous input samples ($x$). Each of these multiplications
- are summed, to produce the result at time $t$. The equation of a FIR
- filter is indeed equivalent to the equation of the dot-product, which is
- shown below:
-
- \begin{equation}
- \mathbf{x}\bullet\mathbf{y} = \sum\nolimits_{i = 0}^{n - 1} {x_i \cdot y_i }
- \end{equation}
-
- We can easily and directly implement the equation for the dot-product
- using higher-order functions:
-
- \begin{code}
- xs *+* ys = foldl1 (+) (zipWith (*) xs hs)
- \end{code}
-
- The \hs{zipWith} function is very similar to the \hs{map} function: It
- takes a function, two vectors, and then applies the function to each of
- the elements in the two vectors pairwise (\emph{e.g.}, \hs{zipWith (*) [1,
- 2] [3, 4]} becomes \hs{[1 * 3, 2 * 4]} $\equiv$ \hs{[3,8]}).
-
- The \hs{foldl1} function takes a function, a single vector, and applies
- the function to the first two elements of the vector. It then applies the
- function to the result of the first application and the next element from
- the vector. This continues until the end of the vector is reached. The
- result of the \hs{foldl1} function is the result of the last application.
- As you can see, the \hs{zipWith (*)} function is just pairwise
- multiplication and the \hs{foldl1 (+)} function is just summation.