I have to code a function to calculate (sum k=1 to n) (-1)^(k+1) * a_k
from list [a_1,a_2,a_3,..a_n]
using foldl
.
calculate list = foldl (\x xs ->
x + (xs * (-1)^(??? + 1))
) 0 list
I managed to write this code, but I don't have a clue what should replace ???
, how to get index of an element in given list.
We can implement this in a more simple way. We can consider a infinite list where we repeat two functions:
id :: a -> a
, andnegate :: Num a => a -> a
, and usecycle :: [a] -> [a]
to construct an infinite list. Socycle [id, negate]
will produce a list that looks like[id, negate, id, negate, ...]
.We can then use
zipWith
to zip the infinite list with the list of values, and use($) :: (a -> b) -> a -> b
as "zip function", so we get:The finally we can use
sum :: Num a => [a] -> a
to sum up these values.So we can define the function as:
For example: