Skip to content

Commit 43437da

Browse files
authored
Added Thomas Algorithm in Haskell (#321)
1 parent 7caac1c commit 43437da

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import Data.List (zip4)
2+
import Data.Ratio
3+
4+
thomas :: Fractional a => [a] -> [a] -> [a] -> [a] -> [a]
5+
thomas a b c = init . scanr back 0 . tail . scanl forward (0, 0) . zip4 a b c
6+
where
7+
forward (c', d') (a, b, c, d) =
8+
let denominator = b - a * c'
9+
in (c / denominator, (d - a * d') / denominator)
10+
back (c, d) x = d - c * x
11+
12+
main :: IO ()
13+
main = do
14+
let a = [0, 2, 3] :: [Ratio Int]
15+
b = [1, 3, 6]
16+
c = [4, 5, 0]
17+
d = [7, 5, 3]
18+
print $ thomas a b c d

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ In the end, we will update $$c$$ and $$d$$ to be $$c'$$ and $$d'$$ like so:
2222
$$
2323
\begin{align}
2424
c'_i &= \frac{c_i}{b_i - a_i \times c'_{i-1}} \\
25-
d'_i &= \frac{d_i - a_i*d'_{i-1}}{b_i - a_i \times c'_{i-1}}
25+
d'_i &= \frac{d_i - a_i \times d'_{i-1}}{b_i - a_i \times c'_{i-1}}
2626
\end{align}
2727
$$
2828

@@ -44,6 +44,8 @@ $$
4444
[import, lang:"c_cpp"](code/c/thomas.c)
4545
{% sample lang="py" %}
4646
[import, lang:"python"](code/python/thomas.py)
47+
{% sample lang="hs" %}
48+
[import, lang:"haskell"](code/haskell/thomas.hs)
4749
{% endmethod %}
4850

4951
This is a much simpler implementation than Gaussian Elimination and only has one for loop before back-substitution, which is why it has a better complexity case.
@@ -70,4 +72,3 @@ $$
7072
\newcommand{\bfomega}{\boldsymbol{\omega}}
7173
\newcommand{\bftau}{\boldsymbol{\tau}}
7274
$$
73-

0 commit comments

Comments
 (0)