What is this fold and iteration?

Imagine that you need to reset the sequence and want to know the intermediate values ​​at several points along the range. This is what I used for this:

[a,b,c] = map fst . tail $ chain [gi, gj, gk] (zero, sequence) g :: Integer -> (a,b) -> (a,b) chain (f:fs) x = x : chain fs (fx) chain [] x = [x] 

The function g consumes a certain part of the input sequence (lengths i , j , etc.), starting from a certain initial value and obtaining the results of the same type, which should be served in the next call. Consuming a sequence several times for different lengths, starting from the beginning and from the same initial value, would be ineffective, both time and space, of course.

So, on the one hand, we add on this sequence of integers - intermediate points on the sequence; on the other hand, we iterate over this function, g . What is it? Am I losing something here? Can this somehow be expressed in a regular repertoire of folds, etc.?

EDIT: Allowed: Above all just

 [a,b,c] = map fst . tail $ scanl (flip g) (zero, sequence) [i, j, k] 

I wonder how a variable iteration actually stacks on a list of modifiers.

+6
source share
2 answers

Try scanl : http://www.haskell.org/hoogle/?hoogle=scanl

scanl is similar to foldl, but returns a list of consecutive abbreviations of the value on the left:

 scanl fz [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] 

note that

 last (scanl fz xs) == foldl fz xs 
+9
source

To clarify Marcin's comment, you basically want to:

 intermediates = scanl step zero sequence map (\n -> intermediates !! n) [i, j, k] 

step not g , but rather the part of g that consumes one element of the sequence list.

Also, accept Marcin as the correct answer.

+4
source

Source: https://habr.com/ru/post/911041/


All Articles