Skip to content

Commit b5a4d1f

Browse files
jiegilletleios
authored andcommitted
Added FFT based convolution in Haskell (#396)
1 parent ea6eb1f commit b5a4d1f

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
1+
import Data.Array.CArray
2+
import Data.Complex
13
import Data.List (tails)
4+
import Math.FFT (dft, idft)
25

36
convolution :: (Num a) => [a] -> [a] -> [a]
47
convolution x = map (sum . zipWith (*) (reverse x)) . spread
5-
where spread = init . tails . (replicate (length x - 1) 0 ++)
8+
where
9+
spread = init . tails . (replicate (length x - 1) 0 ++)
10+
11+
convolutionFFT :: [Complex Double] -> [Complex Double] -> [Complex Double]
12+
convolutionFFT x y = elems $ idft $ liftArray2 (*) (fft x) (fft y)
13+
where
14+
fft a = dft $ listArray (1, length a) a
15+
16+
main :: IO ()
17+
main = do
18+
let x = [1, 2, 1, 2, 1]
19+
y = [2, 1, 2, 1, 2]
20+
print $ convolution x y
21+
print $ convolutionFFT x y

contents/convolutions/convolutions.md

+2-3
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ In code, this looks something like:
3939
{% sample lang="jl" %}
4040
[import:1-17, lang:"julia"](code/julia/conv.jl)
4141
{% sample lang="hs" %}
42-
[import:1-5, lang:"haskell"](code/haskell/convolution.hs)
42+
[import:6-9, lang:"haskell"](code/haskell/convolution.hs)
4343
{% sample lang="c"%}
4444
[import:5-18, lang:"c_cpp"](code/c/convolutions.c)
4545
{% sample lang="cpp"%}
@@ -88,8 +88,7 @@ That said, Julia has an in-built fft routine, so the code for this method could
8888
[import:19-22, lang:"julia"](code/julia/conv.jl)
8989
Where the `.*` operator is an element-wise multiplication.
9090
{% sample lang="hs" %}
91-
The FFT-based convolution in Haskell is complicated, so here is some simple julia code:
92-
[import:19-22, lang:"julia"](code/julia/conv.jl)
91+
[import:11-14, lang:"haskell"](code/haskell/convolution.hs)
9392
Where the `.*` operator is an element-wise multiplication.
9493
{% sample lang="c"%}
9594
[import:20-30, lang:"c_cpp"](code/c/convolutions.c)

0 commit comments

Comments
 (0)