I am trying to use Haskell to read in a list and perform an alternating series, so starting with the first element adding every other and subtracting every other from the second element. For instance [1, 2, 3, 4] would be 1-2+3-4=-2. I thought I had figured out how to do this for lists of a specific length (I wrote it to accommodate empty lists and lists up to 4 elements long), but it doesn't do what I thought it would. It just returns the first element from the list. Here is what I have:
altSeries :: Num a => [a] -> a
altSeries [] = 0
altSeries (x:xs) = if length xs == 1 then x
else if length xs == 2 then x
else if length xs == 3 then (x - xs!!1 + xs!!2)
else (x - xs!!1 + xs!!2 - xs!!3)
Also, what if I wanted to be able to use any list size?
What you want is a list that ultimately looks something like this [1,-2,3,-4] which you could sum.
You can make a list of alternating sign [1,-1]. this can be made infinite using the cycle function. let alternatingSigns = cycle [1,-1]
To transform a list of [1,2,3,4] you can zip the infinite alternating list with your list like this zipWith (*) alternatingSigns input
The whole function would look something like this:
altSeries :: Num a => [a] -> a
altSeries input = let alternatingSigns = cycle [1,-1]
in sum $ zipWith (*) alternatingSigns input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With