iT邦幫忙

2022 iThome 鐵人賽

DAY 11
0

In this exercise, you're implementing a way to keep track of the high scores for the most popular game in your local arcade hall.

1. Define a new high score map

To make a new high score map, define the HighScore.new/0 function which doesn't take any arguments and returns a new, empty map of high scores.

2. Add players to the high score map

To add a player to the high score map, define HighScore.add_player/3, which is a function which takes 3 arguments:

The first argument is the map of scores.
The second argument is the name of a player as a string.
The third argument is the score as an integer. The argument is optional, implement the third argument with a default value of 0.
Store the default initial score in a module attribute. It will be needed again.

3. Remove players from the score map

To remove a player from the high score map, define HighScore.remove_player/2, which takes 2 arguments:

The first argument is the map of scores.
The second argument is the name of the player as a string.

4. Reset a player's score

To reset a player's score, define HighScore.reset_score/2, which takes 2 arguments:

The first argument is the map of scores.
The second argument is the name of the player as a string, whose score you wish to reset.
The function should also work if the player doesn't have a score.

5. Update a player's score

To update a player's score by adding to the previous score, define HighScore.update_score/3, which takes 3 arguments:

The first argument is the map of scores.
The second argument is the name of the player as a string, whose score you wish to update.
The third argument is the score that you wish to add to the stored high score.
The function should also work if the player doesn't have a previous score - assume the previous score is 0.

6. Get a list of players

To get a list of players, define HighScore.get_players/1, which takes 1 argument:

The first argument is the map of scores.


https://exercism.org/tracks/elixir/exercises/high-score

import Map

defmodule HighScore do
  @initial_score 0

  def new(), do: %{}

  def add_player(scores, name, score \\ @initial_score), do: merge(scores, %{ name => score })

  def remove_player(scores, name), do: delete(scores, name)

  def reset_score(scores, name), do: put(scores, name, @initial_score)

  def update_score(scores, name, score), do: update(scores, name, score, fn(old_score) -> old_score + score end)

  def get_players(scores), do: keys(scores)
end

上一篇
十. Recursion
下一篇
十二. Typespecs
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言