Question_Guy
Question_Guy

Reputation: 333

Compute difference between consecutive elements in a given list of integers

I'm using zipWith. i get the correct results but with incorrect signs. How do I fix it? Where am I going wrong?

diff :: [Int] -> [Int]
diff [] = []
diff x = zipWith (-) (tail x) x

result:

diff  [4,2,7,3,6,5]
[-2,5,-4,3,-1]

I want:

[2,-5,4,-3,1]

Upvotes: 0

Views: 932

Answers (1)

pdexter
pdexter

Reputation: 811

As you have it now you're calculating [2-4,7-2,3-7,6-3,5-6]. If you swap the order of your arguments to zipWith (-) x (tail x) then you will correct it to [4-2,2-7,7-3,3-6,6-5]

Upvotes: 4

Related Questions