盒子
盒子
文章目录
  1. Nim编程入门

Nim 语言使用 using 语句简化函数参数

Nim编程入门

Nim 语言提供了 using 语句,使得我们可以简化相同参数的函数定义,但是需要注意不能用于 template

正常定义的函数如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import streams, strutils, sequtils, strformat


type
Graph* = object
data: seq[seq[int]]
vertex, edge: int

proc addEdge*(g: var Graph; v, w: int)

proc initGraph*(vertex: int): Graph =
result.vertex = vertex
result.data = newSeqWith(vertex, newSeq[int]())

proc initGraph*(file: File): Graph =
var strm = newFileStream(file)
let
vertex = parseInt(strm.readLine)
edge = parseInt(strm.readLine)
result = initGraph(vertex)
for i in 0 ..< edge:
let
line = strm.readLine.split
(v, w) = (line[0].parseInt, line[1].parseInt)
result.addEdge(v, w)

proc addEdge*(g: var Graph; v, w: int) =
g.data[v].add(w)
g.data[w].add(v)
g.edge += 1

iterator items*(g: Graph; vertex: int): int =
for item in g.data[vertex]:
yield item

proc vertex*(g: Graph): int =
g.vertex

proc edge*(g: Graph): int =
g.edge

proc `$`*(g: Graph): string =
result.add &"{g.vertex} vertices, {g.edge} edges\n"
for v in 0 ..< g.vertex:
result.add &"{v}: "
for w in g.items(v):
result.add &"{w} "
result.add "\n"


var f = open("graph.txt", fmread)
var g = initGraph(f)
echo g

使用 using 语句,定义参数就可以省略类型了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import streams, strutils, sequtils, strformat


type
Graph* = object
data: seq[seq[int]]
vertex, edge: int

## 使用 using 语句
using
g: Graph
v, w: int
vertex, edge: int

proc addEdge*(g: var Graph; v, w)

proc initGraph*(vertex): Graph =
result.vertex = vertex
result.data = newSeqWith(vertex, newSeq[int]())

proc initGraph*(file: File): Graph =
var strm = newFileStream(file)
let
vertex = parseInt(strm.readLine)
edge = parseInt(strm.readLine)
result = initGraph(vertex)
for i in 0 ..< edge:
let
line = strm.readLine.split
(v, w) = (line[0].parseInt, line[1].parseInt)
result.addEdge(v, w)

proc addEdge*(g: var Graph; v, w) =
g.data[v].add(w)
g.data[w].add(v)
g.edge += 1

iterator items*(g, vertex): int =
for item in g.data[vertex]:
yield item

proc vertex*(g): int =
g.vertex

proc edge*(g): int =
g.edge

proc `$`*(g): string =
result.add &"{g.vertex} vertices, {g.edge} edges\n"
for v in 0 ..< g.vertex:
result.add &"{v}: "
for w in g.items(v):
result.add &"{w} "
result.add "\n"


var f = open("graph.txt", fmread)
var g = initGraph(f)
echo g

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
13 vertices, 13 edges
0: 5 1 2 6
1: 0
2: 0
3: 4 5
4: 3 6 5
5: 0 4 3
6: 4 0
7: 8
8: 7
9: 12 10 11
10: 9
11: 12 9
12: 9 11