F#模块声明

F#模块声明 首页 / F#入门教程 / F#模块声明

F#模块是F#代码构造的组合,如类型,值,函数值和do绑定中的代码,它被实现为仅具有静态成员的公共语言运行时(CLR)类。

根据情况,整个文件是否包含在模块中,有两种类型的模块声明-

  • 顶级模块声明
  • 本地模块声明

在顶层模块声明中,整个文件都包含在模块中,在这种情况下,文件中的第一个声明是模块声明。

无涯教程网

在本地模块声明中,只有在该模块声明下缩进的声明才是模块的一部分。

//顶级模块声明。
module [accessibility-modifier] [qualified-namespace.]module-name
   declarations

//本地模块声明。
module [accessibility-modifier] module-name =
   declarations

请注意,可访问性修饰符可以是以下之一-public,private,internal。默认值为 public 。

示例1

模块文件Arithmetic.fs-

module Arithmetic
let add x y =
   x + y

let sub x y =
   x - y
	
let mult x y =
   x * y
	
let div x y =
   x/y

程序文件main.fs-

//Fully qualify the function name.
open Arithmetic
let addRes = Arithmetic.add 25 9
let subRes = Arithmetic.sub 25 9
let multRes = Arithmetic.mult 25 9
let divRes = Arithmetic.div 25 9

printfn "%d" addRes
printfn "%d" subRes
printfn "%d" multRes
printfn "%d" divRes

编译并执行程序时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-modules.html

来源:LearnFk无涯教程网

34
16
225
2
110
90
1000
10

示例2

//Module1
module module1 =
   //缩进模块中用等号声明的所有程序元素。
   let value1 = 100
   let module1Function x =
      x + value1

//Module2
module module2 =
   let value2 = 200

   //使用限定名称访问该函数。
   //from module1.
   let module2Function x =
      x + (module1.module1Function value2)

let result = module1.module1Function 25
printfn "%d" result

let result2 = module2.module2Function 25
printfn "%d" result2

编译并执行程序时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-modules.html

来源:LearnFk无涯教程网

125
325

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

超级访谈:对话道哥 -〔吴翰清(道哥)〕

快手 · 音视频技术入门课 -〔刘歧〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

MySQL 必知必会 -〔朱晓峰〕

跟月影学可视化 -〔月影〕

Service Mesh实战 -〔马若飞〕

分布式技术原理与算法解析 -〔聂鹏程〕

Linux性能优化实战 -〔倪朋飞〕

快速上手Kotlin开发 -〔张涛〕

好记忆不如烂笔头。留下您的足迹吧 :)