how to do a recursive function in haskell that takes a list of numbers and calculates the average value (truncated, using whole division)?

0

I have to do the following recursive function, but it throws me error. What's wrong?

promedio :: [Int] -> Int, que toma una lista de numeros y calcula el valor pro-
medio (truncado, usando division entera).

promedio :: [Int] -> Int

promedio[]= 0

promedio (x:xs) = x /(length xs) + promedio (xs)

This error appears on the console:

  

Main > average1 [2, 3, 3, 5, 7, 10] *** Exception: divide by zero

and I had to use div instead of / because I got a lot of errors

    
asked by Diego 15.08.2018 в 07:55
source

1 answer

1

You could use integer division for the sum of a set:

promedio xs = sum xs 'div' length xs

Recursively:

promedio :: [Int] -> Int  
promedio[]= 0  
promedio (x:xs) = if (length xs > 0) then (x + promedio(xs)) 'div' 2 else x

The result of the entire division will be truncated downwards.

    
answered by 15.08.2018 в 11:11