iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
Software Development

戀戀 Elixir系列 第 8

八.Multiple Clause Functions

  • 分享至 

  • xImage
  •  

You are creating a trivial online game where a friend can guess a secret number. You want to give some feedback, but not give away the answer with a guess. You need to devise a function to provide different responses depending on how the guess relates to the secret number.

All guesses and secret numbers are integer numbers.

1. Make the response when the guess matches the secret number

Implement the compare/2 function which takes two arguments, secret_number and guess, which are both integers.

2. Make the response when the guess is greater than the secret number

Modify the compare function to respond to guesses that are higher than the secret number.

3. Make the response when the guess is less than the secret number

Modify the compare function to respond to guesses that are lower than the secret number.

4. Make the responses when the guess is one more or one less than the secret number

Modify the compare function to respond to guesses that are close to the secret number.

5. Make the response when there is no guess

Modify the compare function to respond to a lack of guess.


https://exercism.org/tracks/elixir/exercises/guessing-game

defmodule GuessingGame do
  def compare(_, guess \\ :no_guess)

  def compare(_, guess) when guess === :no_guess, do: "Make a guess"

  def compare(secret_number, guess) when secret_number === guess, do: "Correct"

  def compare(secret_number, guess) when secret_number + 1 < guess, do: "Too high"

  def compare(secret_number, guess) when secret_number - 1 > guess, do: "Too low"

  def compare(secret_number, guess) when guess in [secret_number + 1, secret_number - 1] , do: "So close"
end


上一篇
七. Lists
下一篇
九.Tuples
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言