SML лаба

  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
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
datatype Pattern
= SEQUENCE of Term list
and Term
= SYM_LETTER of char
| SYM_WORD of string
| SYM_NUMBER of int
| STRUC of Pattern
| VAR of char * string
fun processPattern getAtom handlStruct operation (SEQUENCE pattern) =
let
fun proc ((STRUC (SEQUENCE x)) :: nil) = handlStruct (proc x)
| proc ((STRUC (SEQUENCE x)) :: xs) = operation (handlStruct (proc x), proc xs)
| proc (x :: nil) = getAtom x
| proc (x :: xs) = operation (getAtom x, proc xs)
in
proc pattern
end
fun rename pattern (VAR (x, y)) newIndex =
let
val oldx = x;
val oldy = y;
fun getAtom (VAR (x, y)) = (if x = oldx andalso y = oldy then [VAR (oldx, newIndex)] else [VAR (x, y)])
| getAtom x = [x]
fun handlStruct x = [(STRUC (SEQUENCE x))]
in
SEQUENCE (processPattern getAtom handlStruct (op @) pattern)
end
fun getVariables pattern =
let
fun getAtom (VAR (x, y)) = [(x, y)]
| getAtom _ = []
fun handlStruct x = x
in
processPattern getAtom handlStruct (op @) pattern
end
fun getString pattern =
let
fun getAtom (VAR (x, y)) = Char.toString x ^ "." ^ y ^ " "
| getAtom (SYM_WORD x) = x ^ " "
| getAtom (SYM_LETTER x) = Char.toString x ^ " "
| getAtom (SYM_NUMBER x) = Int.toString x ^ " "
fun handlStruct x = "( " ^ x ^ " ) "
in
processPattern getAtom handlStruct (op ^) pattern
end
fun getDepth pattern =
let
fun getAtom _ = 0
fun handlBracket x = 1 + x
in
1 + processPattern getAtom handlBracket (op +) pattern
end
val testTree1 =
(SEQUENCE [
SYM_LETTER(#"a"),
SYM_NUMBER 888,
VAR(#"t", "Term"),
VAR(#"s", "Char1"),
STRUC(SEQUENCE[
SYM_LETTER(#"a"),
VAR(#"s", "Char2"),
SYM_LETTER(#"b"),
SYM_WORD("word"),
STRUC(SEQUENCE[
SYM_LETTER(#"a"),
VAR(#"s", "Char2"),
SYM_LETTER(#"b"),
SYM_WORD("word")
]),
STRUC(SEQUENCE[
SYM_LETTER(#"a"),
VAR(#"s", "Char2"),
SYM_LETTER(#"b"),
SYM_WORD("word")
])
]),
STRUC(SEQUENCE[
SYM_LETTER(#"a"),
VAR(#"s", "Char2"),
SYM_LETTER(#"b"),
SYM_WORD("word"),
STRUC(SEQUENCE[
SYM_LETTER(#"a"),
VAR(#"s", "Char2"),
SYM_LETTER(#"b"),
SYM_WORD("word")
]),
STRUC(SEQUENCE[
SYM_LETTER(#"a"),
VAR(#"s", "Char2"),
SYM_LETTER(#"b"),
SYM_WORD("word")
])
])
]);
val Variables = getVariables testTree1;
val Depth = getDepth testTree1;
val Renamed = rename testTree1 (VAR(#"s", "Char2")) "newname";
val String = getString Renamed;
print String;