Reputation: 27
i need to do a subtraction in haskell, and the result add an list, but the new list doesn't give me the real valors
for example: [1,2,3,4,5]
prom = (1 + 2 + 3 + 4 + 5) / 5 = 3
subs = (1 - 3) = -2 add to list
subs = (2 - 3) = -1 add to list
subs = (3 - 3) = 0 add to list
subs = (4 - 3) = 1 add to list
subs = (5 - 3) = 2 add to list
new list = [-2,-1,0,1,2]
this's the code:
add (x:xs) = x + add xs
prom (x:xs) = add (x:xs) `div` length (x:xs)
subs [] = []
subs (x:xs) = x - prom (x:xs) : subs xs
how i can do that? and why the results is different?
Upvotes: 1
Views: 473
Reputation: 476584
prom (x:xs)
will return the average for that list, but if you recurse, you thus consider the tail of the list, and you thus calculate the average on the remaining elements.
This means that your list will contain [1-3, 2-3, 3-4, 4-4, 5-5]
, so [-2, -1, -1, 0, 0]
. You should thus determine the average of the entire list, and subtract that from all elements, so:
subs :: [Int] -> [Int]
subs xs = map (subtract (prom xs)) xs
Your add
should also consider the empty list case:
add :: [Int] -> Int
add [] = 0
add (x:xs) = x + add xs
and for prom
you can work with an xs
variable as pattern to bind with the entire list:
prom :: [Int] -> Int
prom xs = add xs `div` length xs
Upvotes: 4