c++ - What container really mimics std::vector in Haskell? -
the problem
i'm looking container used save partial results of n - 1
problems in order calculate n
th one. means size of container, @ end, n
.
each element, i
, of container depends on @ least 2 , 4 previous results.
the container have provide:
- constant time insertions @ either beginning or end (one of two, not both)
- constant time indexing in middle
or alternatively (given o(n)
initialization):
- constant time single element edits
- constant time indexing in middle
what std::vector
, why relevant
for of don't know c++, std::vector
dynamically sized array. perfect fit problem because able to:
- reserve space @ construction
- offer constant time indexing in middle
- offer constant time insertion @ end (with reserved space)
therefore problem solvable in o(n)
complexity, in c++.
why data.vector
not std::vector
data.vector
, data.array
, provide similar functionality std::vector
, not quite same. both, of course, offer constant time indexing in middle, offer neither constant time modification ((//)
example @ least o(n)
) nor constant time insertion @ either beginning of end.
conclusion
what container mimics std::vector
in haskell? alternatively, best shot?
from reddit comes suggestion use data.vector.constructn
:
o(n) construct vector n elements repeatedly applying generator function constructed part of vector.
constructn 3 f = let = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c>
for example:
λ import qualified data.vector v λ v.constructn 10 v.length fromlist [0,1,2,3,4,5,6,7,8,9] λ v.constructn 10 $ (1+) . v.sum fromlist [1,2,4,8,16,32,64,128,256,512] λ v.constructn 10 $ \v -> let n = v.length v in if n <= 1 1 else (v v.! (n - 1)) + (v v.! (n - 2)) fromlist [1,1,2,3,5,8,13,21,34,55]
this seems qualify solve problem you've described above.
Comments
Post a Comment