Haskell中的两个参数记忆 [英] Two parameter memoization in Haskell

查看:81
本文介绍了Haskell中的两个参数记忆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图记住下面的函数:

  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中的多个参数记忆函数吗?使用 / hackage.haskell.org/packages/archive/data-memocombinators/0.4.1/doc/html/Data-MemoCombinators.html\">data-memocombinators 软件包。它提供了易于使用的记忆技术,并提供了一种简单易用的方法来使用它们:

  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中的两个参数记忆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆