distro.obs
distro.obs

Reputation: 181

Haskell - A better way of generating a new list (like folding) without folding

If foldl is given a function (+) and a list [1..10] it'll generate a final number.


What I want is given

[1,2,3,4,5,6,7,8,9,10]

output would be the Triangular Number series.

but given a list like

[3, 5, 1, 4, 7, 8, 10]

output would be

[3, 8, 9, 13, 20, 28, 38]

The way I'm doing that is generating a new list by using

sum (take x) list

where x is the current index

and appending it to the new list.


Is there a better way of doing this?

Upvotes: 0

Views: 73

Answers (2)

bipll
bipll

Reputation: 11940

If you look at PreludeList, you'll notice function scanl right next to foldl (and scanl1 to counter foldl1). Is that what you need perhaps?

Prelude> scanl1 (+) [3, 5, 1, 4, 7, 8, 10]
[3,8,9,13,20,28,38]

Though it would not generate Fibonacci out of positive integers.

Upvotes: 5

chepner
chepner

Reputation: 531345

You are looking for the scanl1 function:

> scanl1 (+) [3,5,1,4,7,8,10]
[3,8,9,13,20,28,38]

Upvotes: 2

Related Questions