Memoization pascals triangle

后端 未结 3 916
春和景丽
春和景丽 2020-12-20 07:55

I\'m not interested in the actual solution or other methods solving the problem, it\'s the memoization i need help with :)

I need help doing a pascals triangle probl

3条回答
  •  眼角桃花
    2020-12-20 08:33

    zmemopascals r c =  zipWith pascals [1 ..] [1 ..] !! (r-1) !! (c-1) 
     where pascals 1 _ = 1 
           pascals _ 1 = 1 
           pascals x y = memopascals (x-1) y + memopascals x (y-1)
    

    Not that it matters for the error, but in the last line, you want to call zmemopascals rather than memopascals.

    In the first line, you have two list index operators. So zipWith pascals [1 .. ] [1 .. ] must have type [[a]] for some a. The definition of pascals says

    pascals :: Num t => Int -> Int -> t
    

    thus zipWith pascals [1 .. ] [1 .. ] :: [t]. Hence the type inference finds that t = [a], but the compiler doesn't find an instance Num [a].

    For memoisation, you have to give a name to the full triangle, like @sth suggested, to avoid recomputation (the Fibonacci memoisation only works because the compiler is smart enough, it's not guaranteed by its form).

    Another option would be to construct the triangle using iterate,

    pascal :: Int -> Int -> Integer
    pascal n k = iterate nextRow [1] !! n !! k
      where
        nextRow ks = zipWith (+) (0:ks) (ks ++ repeat 0)
    

提交回复
热议问题