From 61c9288a41c0425b45070900515c53605a47549b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Gillet?= Date: Wed, 1 Aug 2018 21:32:07 +0900 Subject: [PATCH] Added Thomas Algorithm in Haskell --- .../thomas_algorithm/code/haskell/thomas.hs | 18 ++++++++++++++++++ contents/thomas_algorithm/thomas_algorithm.md | 5 +++-- 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 contents/thomas_algorithm/code/haskell/thomas.hs diff --git a/contents/thomas_algorithm/code/haskell/thomas.hs b/contents/thomas_algorithm/code/haskell/thomas.hs new file mode 100644 index 000000000..7610ff63f --- /dev/null +++ b/contents/thomas_algorithm/code/haskell/thomas.hs @@ -0,0 +1,18 @@ +import Data.List (zip4) +import Data.Ratio + +thomas :: Fractional a => [a] -> [a] -> [a] -> [a] -> [a] +thomas a b c = init . scanr back 0 . tail . scanl forward (0, 0) . zip4 a b c + where + forward (c', d') (a, b, c, d) = + let denominator = b - a * c' + in (c / denominator, (d - a * d') / denominator) + back (c, d) x = d - c * x + +main :: IO () +main = do + let a = [0, 2, 3] :: [Ratio Int] + b = [1, 3, 6] + c = [4, 5, 0] + d = [7, 5, 3] + print $ thomas a b c d diff --git a/contents/thomas_algorithm/thomas_algorithm.md b/contents/thomas_algorithm/thomas_algorithm.md index 8915d3028..2be5b674e 100644 --- a/contents/thomas_algorithm/thomas_algorithm.md +++ b/contents/thomas_algorithm/thomas_algorithm.md @@ -22,7 +22,7 @@ In the end, we will update $$c$$ and $$d$$ to be $$c'$$ and $$d'$$ like so: $$ \begin{align} c'_i &= \frac{c_i}{b_i - a_i \times c'_{i-1}} \\ -d'_i &= \frac{d_i - a_i*d'_{i-1}}{b_i - a_i \times c'_{i-1}} +d'_i &= \frac{d_i - a_i \times d'_{i-1}}{b_i - a_i \times c'_{i-1}} \end{align} $$ @@ -44,6 +44,8 @@ $$ [import, lang:"c_cpp"](code/c/thomas.c) {% sample lang="py" %} [import, lang:"python"](code/python/thomas.py) +{% sample lang="hs" %} +[import, lang:"haskell"](code/haskell/thomas.hs) {% endmethod %} 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 @@ $$ \newcommand{\bfomega}{\boldsymbol{\omega}} \newcommand{\bftau}{\boldsymbol{\tau}} $$ -