练习 - 函数
在此练习中,你将使代码可重复使用。 代码是团队中的另一个程序员编写的,但你的工作是将其转换为函数。
创建函数
首先,搭建一个新的 F# 项目基架,然后取用一段代码并将其转换为具有参数的函数。
通过运行
dotnet new来创建新的 F# 项目。dotnet new console --language F# -o Functions cd Functions现在你有了一个新项目,来看一下代码。
这是你的同事编写的代码。
let no = card % 13 if no = 1 then "Ace" elif no = 0 then "King" elif no = 12 then "Queen" elif no = 11 then "Jack" else string no将 Program.fs 文件中的默认代码替换为以下代码:
let cardFace card = let no = card % 13 if no = 1 then "Ace" elif no = 0 then "King" elif no = 12 then "Queen" elif no = 11 then "Jack" else string no这段代码的第一行
let cardFace card使其成为一个函数。 它现在是名为cardface()的函数,并采用参数card。将以下代码添加到
cardface()函数下。printfn "%s" (cardFace 11)在控制台中通过调用
dotnet run来运行项目。dotnet run现在会看到以下输出:
Jack
祝贺你! 你已获取一段想要重用的代码,并将其转换为函数。
添加类型
你已将同事的代码转换为函数。 为了使此代码更便于阅读,你决定向其中添加类型定义。
修改现有函数
cardface(),使它看起来像下面这样:let cardFace (card:int) = let no = card % 13 if no = 1 then "Ace" elif no = 0 then "King" elif no = 12 then "Queen" elif no = 11 then "Jack" else string no现在运行项目
dotnet run。dotnet run现在会看到以下输出:
Jack此代码依然正常运行,你只是在输入参数中添加了一个类型,使其更明晰。
修改
cardface()函数,如下所示:let cardFace (card:int) :string = let no = card % 13 if no = 14 || no = 1 then "Ace" elif no = 13 then "King" elif no = 12 then "Queen" elif no = 11 then "Jack" else string no此时,已在函数
:string中添加了一个返回类型,这意味着该函数会返回字符串。运行项目
dotnet run。dotnet run应会再次看到以下输出:
Jack
祝贺你! 你的代码中现在已经添加了类型。