Calculating the average score for the top N stories

Now that we have the ability to find the top stories and retrieve details about each story, we can create a new function to calculate an average score from the top N stories.

The average_score function is as follows:

using Statistics: mean

function average_score(n = 10)
story_ids = fetch_top_stories()
println(now(), " Found ", length(story_ids), " stories")

top_stories = [fetch_story(id) for id in story_ids[1:min(n,end)]]
println(now(), " Fetched ", n, " story details")

avg_top_scores = mean(s.score for s in top_stories)
println(now(), " Average score = ", avg_top_scores)

return avg_top_scores
end

There are three parts to this function:

  1. The first part finds the story IDs for top stories using the fetch_top_stories function. 
  2. Then, it retrieves details of the first n stories using the fetch_story function.
  3. Finally, it calculates the average score from just those stories. Then, the average score is returned to the caller.

In order to get the top n story IDs, we have chosen to use the index operator with the range 1:min(n,end). The min function is used to handle the case when n is greater than the size of the array.

Let's run the function and see what happens:

From the result, we can see that the top n stories from Hacker News have an average score of 125.4. Note that you may get a different result since this number changes in real time as Hacker News users vote on their favorite stories.

Now that the use case has been established, we will leap forward and experiment with a different way of writing the same program. We call this style of programming functional pipes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.156.35