Sudan function: Difference between revisions

Initial Haskell version.
(added AWK)
(Initial Haskell version.)
Line 430:
<pre>
Identical to Wren example.
</pre>
 
=={{header|Haskell}}==
<lang haskell>import Control.Monad.Memo (Memo, memo, startEvalMemo)
import Data.List.Split (chunksOf)
import System.Environment (getArgs)
import Text.Tabular (Header(..), Properties(..), Table(..))
import Text.Tabular.AsciiArt (render)
 
type SudanArgs = (Int, Integer, Integer)
 
-- Given argument (n, x, y) calculate Fₙ(x, y). For performance reasons we do
-- the calculation in a memoization monad.
sudan :: SudanArgs -> Memo SudanArgs Integer Integer
sudan (0, x, y) = return $ x + y
sudan (_, x, 0) = return x
sudan (n, x, y) = memo sudan (n, x, y-1) >>= \x2 -> sudan (n-1, x2, x2 + y)
 
-- A table of Fₙ(x, y) values, where the rows are y values and the columns are
-- x values.
sudanTable :: Int -> [Integer] -> [Integer] -> String
sudanTable n xs ys = render show show show
$ Table (Group NoLine $ map Header ys)
(Group NoLine $ map Header xs)
$ chunksOf (length xs)
$ startEvalMemo
$ sequence
$ [sudan (n, x, y) | y <- ys, x <- xs]
 
main :: IO ()
main = do
args <- getArgs
case args of
[n, xlo, xhi, ylo, yhi] -> do
putStrLn $ "Fₙ(x, y), where the rows are y values " ++
"and the columns are x values.\n"
putStr $ sudanTable (read n)
[read xlo .. read xhi]
[read ylo .. read yhi]
_ -> error "Usage: sudan n xmin xmax ymin ymax"</lang>
{{out}}
<pre>
$ sudan 0 0 5 0 6
Fₙ(x, y), where the rows are y values and the columns are x values.
 
+---++---------------+
| || 0 1 2 3 4 5 |
+===++===============+
| 0 || 0 1 2 3 4 5 |
| 1 || 1 2 3 4 5 6 |
| 2 || 2 3 4 5 6 7 |
| 3 || 3 4 5 6 7 8 |
| 4 || 4 5 6 7 8 9 |
| 5 || 5 6 7 8 9 10 |
| 6 || 6 7 8 9 10 11 |
+---++---------------+
$ sudan 1 0 5 0 6
Fₙ(x, y), where the rows are y values and the columns are x values.
 
+---++-------------------------+
| || 0 1 2 3 4 5 |
+===++=========================+
| 0 || 0 1 2 3 4 5 |
| 1 || 1 3 5 7 9 11 |
| 2 || 4 8 12 16 20 24 |
| 3 || 11 19 27 35 43 51 |
| 4 || 26 42 58 74 90 106 |
| 5 || 57 89 121 153 185 217 |
| 6 || 120 184 248 312 376 440 |
+---++-------------------------+
</pre>
 
Anonymous user