I really need help finding a way to calculate the average in miranda language. I seem to get this error that it cannot unify the type [num] -> num with num. I can't seem to take the sum of the list as a value and do division?
elements = 4
grades = [24, 12, 33, 17]
|| The code belows purpose is to get the sum of the list
ngrades == [num]
sumlist :: ngrades -> num
sumlist [] = 0
sumlist (front : rest) = front + sumlist rest
|| We calculate the average by getting the sum we calc above to the elements
avg = sumlist div elements
|| We compare each element reccursively to find the maximum value
maxi :: ngrades -> num
maxi [] = 0
maxi (front : []) = front[][1]
maxi (front : next : rest) = maxi (front : rest), if front > next
= maxi (next : rest), otherwise
|| We compare each element reccursively to find the minimum value
mini :: ngrades -> num
mini [] = 0
mini (front : []) = front
mini (front : next : rest) = mini (front : rest), if front < next
= mini (next : rest), otherwise
[1]: https://i.stack.imgur.com/2pYCq.jpg
Miranda has a list a standard library functions. For your problem, following two are of interest:
Sum up all elements of numeric list:
Count all elements of any list:
You can simply write a function to calculate the average:
First pattern catches empty list. Second pattern calculates sum and count, then divides both into floating number.
I am used to name lists as "xs".
Example of usage:
This simple solution works on every finite list. If list is really long, you scan it twice (once to get sum, second to count elements). This can be reduced to single scan.
BTW: Your code will work, if you change:
into: