简体   繁体   English

使用Data.Vector进行动态编程

[英]Dynamic programming with Data.Vector

am using Data.Vector and am currently in need of computing the contents of a vector for use in computing a cryptographic hash(Sha1). 我正在使用Data.Vector,目前需要计算向量的内容,以便用于计算加密哈希(Sha1)。 I created the following code. 我创建了以下代码。

dynamic :: a -> Int -> (Int -> Vector a -> a) -> Vector a
dynamic e n f = 
let 
    start = Data.Vector.replicate n e   
in step start 0
where
    step vector i = if i==n then vector
                    else step (vector // [(i,f i vector)]) (i+1)

I created this so that the function f filling out the vector has access to the partial results along the way. 我创建了这个,以便填充向量的函数f可以访问沿途的部分结果。 Surely something like this must already exist in Data.Vector, no? 当然这样的东西必须已经存在于Data.Vector中,不是吗?

The problem statement is the following: You are to solve a dynamic programming problem where the finished result is an array. 问题陈述如下:您将解决动态编程问题,其中完成的结果是数组。 You know the size of the array size and you have a recursive function for filling it out. 你知道数组大小的大小,你有一个递归函数来填充它。

You probably already saw the function generate , which takes a size n and a function f of type Int -> a and then produces a Vector a of size n . 您可能已经看到函数generate ,它接受大小为n和类型为Int -> a的函数f ,然后生成大小为nVector a What you probably weren't aware of is that when using this function you actually do have access to the partial results. 您可能不知道的是,在使用此功能时,您实际上可以访问部分结果。

What I mean to say is that inside the function you pass to generate you can refer to the vector you're defining and due to Haskell's laziness it will work fine (unless you make it so that the different items of the vector depend on each other in a circular fashion, of course). 我的意思说的是,在函数内部传递给generate你可以参考你定义的矢量和由于Haskell的懒惰它会正常工作(除非你让这个载体的不同的项目互相依赖当然是循环的)。

Example: 例:

import Data.Vector

tenFibs = generate 10 fib
    where fib 0 = 0
          fib 1 = 1
          fib n = tenFibs ! (n-1) + tenFibs ! (n-2)

tenFibs is now a vector containing the first 10 Fibonacci numbers. tenFibs现在是一个包含前10个Fibonacci数的向量。

Maybe you could use one of Data.Vector's scan functions? 也许您可以使用Data.Vector的扫描功能之一? http://hackage.haskell.org/packages/archive/vector/0.6.0.2/doc/html/Data-Vector.html#32 http://hackage.haskell.org/packages/archive/vector/0.6.0.2/doc/html/Data-Vector.html#32

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM