How to define an infinite 2D array recursively in Haskell?

I am new to Haskell and I like his graceful literacy. But I did not find a suitable way to define an infinite 2D array - for example, the Pascal Triangle:

1  1  1  1  1  ...
1  2  3  4  5  ...
1  3  6 10 15  ...
1  4 10 20 35  ...
1  5 15 35 70  ...
...

I know how to define a simple function:

pascal :: Int -> Int -> Int
pascal 1 _ = 1
pascal _ 1 = 1
pascal x y = (pascal (x - 1) y) + (pascal x (y - 1))

Since Haskell does not remember function values, the call pascal 20 20will take a long time. How can I define a fast version (like an infinite 2D array)?

+4
source share
2 answers

You can create a pascal triangle as an infinite, lazy, nested list

pascal :: [[Integer]]
pascal = repeat 1 : map (scanl1 (+)) pascal

, , , repeat 1 .. . , , O (n).

, , .

> pascal !! 19 !! 19
35345263800

, .

:

> putStrLn $ unlines $ take 5 $ map (unwords . map show . take 5) $ pascal
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70

, memoize . , data-memocombinators:

import Data.MemoCombinators

pascal :: Integer -> Integer -> Integer
pascal = memo2 integral integral pascal'

pascal' :: Integer -> Integer -> Integer
pascal' 1 _ = 1
pascal' _ 1 = 1
pascal' x y = (pascal (x - 1) y) + (pascal x (y - 1))
+9

"" , .. .

pascal' :: [[Integer]]
pascal' = repeat 1 : [ 1 : [ pascalGen x y | y<-[1..] ] | x<-[1..] ]
 where pascalGen x y = pascal' !! (x-1) !! y + pascal' !! x !! (y - 1)

memoised. - O (n), .

+3

All Articles