这个Haskell函数会记住吗? [英] Does this Haskell function memoize?

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

问题描述

我想预先计算一些值,然后在需要进行进一步查找时使用这些值.我提出了以下建议:

I'd like to pre-calculate some values that are then used when I need to do further lookups. I came up with the following:

import qualified Data.Vector.Unboxed as V

lcgen s =
  lc
  where
    lc 0 b  = lengths V.! b
    lc a b  = lengths V.! b - lengths V.! (a - 1) - 1
    lengths = V.fromList $ scanl1 ((+) . (1 +)) $ map length $ words s

该函数本质上返回两个单词之间使用的字符数.我使用它的方式如下:

The function essentially returns the number of characters used in-between two words. I use it as follows:

let lc = lcgen "some sentence with a lot of words"
lc 0 0 -- == 4
lc 0 1 -- == 13

在此实现中,会记住lengths向量吗?此外,我怎么知道和/或确认这一点?

In this implementation, would the lengths vector be memoized? Furthermore, how can I know and/or confirm this?

推荐答案

(如果您添加

if you add a trace to your lengths like this:

lengths = trace "building list..." $ V.fromList ...

每次计算lengths值时,您都会看到输出

you will see the output every time the lengths value is calculated

按原样,每个lc = lcgen s

这篇关于这个Haskell函数会记住吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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