问题描述
我试图记住下面的函数: gridwalk x y
| x == 0 = 1
| y == 0 = 1
|否则=(gridwalk(x-1)y)+(gridwalk x(y - 1))
看看我想出了以下解决方案:
gw ::(Int→> Int→> Int) - > Int - > Int - > Int
gw f x y
| x == 0 = 1
| y == 0 = 1
|否则=(f(x-1)y)+(fx(y-1))
gwlist :: [Int]
gwlist = map(\i- - > gw fastgw (i`mod` 20)(i`div` 20))[0 ..]
fastgw :: Int - > Int - > Int
fastgw x y = gwlist !! (x + y * 20)
然后我可以这样调用:
gw fastgw 20 20
是否有一个更简单,更简洁和一般的方法(请注意,为了将2D空间转换为1D空间,我必须对 gwlist
函数中的最大网格维度进行硬编码,以便可以访问记忆列表)用Haskell中的多个参数记忆函数吗?使用软件包。它提供了易于使用的记忆技术,并提供了一种简单易用的方法来使用它们:
import Data.MemoCombinators(memo2,integral )
gridwalk = memo2积分积分gridwalk'其中
gridwalk'xy
| x == 0 = 1
| y == 0 = 1
|否则=(gridwalk(x-1)y)+(gridwalk x(y - 1))
I'm trying to memoize the following function:
gridwalk x y
| x == 0 = 1
| y == 0 = 1
| otherwise = (gridwalk (x - 1) y) + (gridwalk x (y - 1))
Looking at this I came up with the following solution:
gw :: (Int -> Int -> Int) -> Int -> Int -> Int
gw f x y
| x == 0 = 1
| y == 0 = 1
| otherwise = (f (x - 1) y) + (f x (y - 1))
gwlist :: [Int]
gwlist = map (\i -> gw fastgw (i `mod` 20) (i `div` 20)) [0..]
fastgw :: Int -> Int -> Int
fastgw x y = gwlist !! (x + y * 20)
Which I then can call like this:
gw fastgw 20 20
Is there an easier, more concise and general way (notice how I had to hardcode the max grid dimensions in the gwlist
function in order to convert from 2D to 1D space so I can access the memoizing list) to memoize functions with multiple parameters in Haskell?
Use the data-memocombinators package from hackage. It provides easy to use memorization techniques and provides an easy and breve way to use them:
import Data.MemoCombinators (memo2,integral)
gridwalk = memo2 integral integral gridwalk' where
gridwalk' x y
| x == 0 = 1
| y == 0 = 1
| otherwise = (gridwalk (x - 1) y) + (gridwalk x (y - 1))
这篇关于Haskell中的两个参数记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!