Visit the two-fer exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
Option.defaultValue
Option.defaultValue
let twoFer (nameOpt: string option): string =
let name = Option.defaultValue "you" nameOpt
$"One for {name}, one for me."
We use the Option.defaultValue function which either returns the value within the Option<T> value passed to it, or else returns the default value we pass to it ("you").
We then use string interpolation to build the return string where {name} is replaced with the name we just found.
The string formatting article discusses alternative ways to format the returned string.
Pattern matching
Pattern matching
module TwoFer
let twoFer (nameOpt: string option): string =
let name =
match nameOpt with
| Some name -> name
| None -> "you"
$"One for {name}, one for me."
We use pattern matching to get the name we need to use in our greeting:
Some name matches when a name was specified. In this case, we’ll just return that name
None matching when no name was specified. We’ll return "you" in this case
We then use string interpolation to build the return string where {name} is replaced with the name we just found.
The string formatting article discusses alternative ways to format the returned string.
Lihat Solusi Komunitas
The following are the top 3 community solutions by stars:
Source: Exercism fsharp/two-fer