Average value for ints

I am new to Haskell and Stackoverflow, and I am trying to teach Haskell programming, and I am doing a series of exercises from a book that I downloaded, and I was wondering if you guys could help me here.

I am trying to write an avgPub function that returns the average of all years of publication for a series of books. Function arguments: avgPub :: [(String, String, Int)] → Int. An example of I / O is

> avgPub [("publisher", "book", 1920), ("publisher1", "book1", 1989), ("publisher2", "book2", 1920)]
1943

Yesterday I found out about div, sum and map, but I'm not sure how to tie it all together for this problem (as the exercise hints). I think that in order to find the average value of the Ints list, you make a list (x:xs) = (sum (x:xs))div length, but we are not only dealing with Ints, so this will not work.

I find it difficult to figure out how to tie it all together.

+4
source share
3 answers

You are on the right track with year' :: [(String, String, Int)] -> Int. You want to somehow extract the year field from all records in order to average them.

The easiest way to do this is to write a function that takes one record and retrieves a year. That is, for example:

year :: (String, String, Int) -> Int
year (_, _, i) = i

(note that the first argument is not a list)

Then you can do another function yearsto get the list Intfrom the list of entries:

years :: [(String, String, Int)] -> [Int]
years xs = map year xs

Then all you have to do is combine it with the code to calculate the average of the list Ints:

average :: [Int] -> Int
average xs = (sum xs) `div` (length xs)

To relate this:

avgPub books = average (years books)
+2
source

Prompt:

year' :: [(String, String, Int)] -> [Int]
year' = map (\(_,_,i) -> i)

Oh, and if you find something that works, put it on https://codereview.stackexchange.com/ , as you say that you are new to Haskell.

0

" ", , :

avgPub books = result where
    result = average yearlist
    yearlist = map year' books

avgPub = average . map year'
0

Source: https://habr.com/ru/post/1570792/


All Articles