Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell foldr and variable

How can I make a function similar to this but with n being a variable with a number beginning in 1 and ending with the value of the length of xs?

For Example I want [1,2,3] to return the result of 3*1 + 2*2 + 1*3.

function :: [Int] -> Int
function xs = foldr (\x acc -> (x*n) + acc) 0 xs
like image 452
Rance Avatar asked Nov 24 '25 08:11

Rance


1 Answers

A idiomatic Haskell answer can be:

function = sum . zipWith (*) [1 ..] . reverse

Reading from right to left: you reverse the list (reverse), doing so you won't need to count backward (from n to 1) but forward (1 to n)... then you zip it with the index using * (zipWith (*) [1..]) and finally sou sum things up (sum).

like image 106
Nicolas Avatar answered Nov 27 '25 03:11

Nicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!