Define functions and, or, nand, nor, xor, impl, and equ (for logical equivalence) which return true or false according to the result of their respective operations; e.g. and(A, B) is true if and only if both A and B are true.
1
2
3
4
5
scala> and(true, true)
res0: Boolean = true
scala> xor(true. true)
res1: Boolean = false
A logical expression in two variables can then be written as an function of two variables, e.g: (a: Boolean, b: Boolean) => and(or(a, b), nand(a, b))
Now, write a function called table2 which prints the truth table of a given logical expression in two variables.
def impl(a: Boolean, b: Boolean): Boolean = or(not(a), b)
def table2(f: (Boolean, Boolean) => Boolean) {
println("A B result")
for (
a <- List(true, false);
b <- List(true, false)
) {
printf("%-5s %-5s %-5s\n", a, b, f(a, b))
}
}
}
P47 (*) Truth tables for logical expressions (2).
要求
Continue problem P46 by redefining and, or, etc as operators. (i.e. make them methods of a new class with an implicit conversion from Boolean.) not will have to be left as a object method.
1
2
3
4
5
6
scala> table2((a: Boolean, b: Boolean) => a and (a or not(b)))
AB result
truetruetrue
truefalsetrue
falsetruefalse
falsefalsefalse
代码
按要求需要将布尔值隐式转换为该类型对象以支持中缀操作符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
classS99Logic(a: Boolean) {
importS99Logic._
defand(b: Boolean): Boolean = (a, b) match {
case (true, true) => true
case _ => false
}
defor(b: Boolean): Boolean = (a, b) match {
case (true, _) => true
case (_, true) => true
case _ => false
}
defequ(b: Boolean): Boolean = (a and b) or (not(a) and not(b))
See if you can use memoization to make the function more efficient.
代码
P50 (*) Huffman code.
霍夫曼码
要求
First of all, consult a good book on discrete mathematics or algorithms for a detailed description of Huffman codes! We suppose a set of symbols with their frequencies, given as a list of (S, F) Tuples. E.g. ((“a”, 45), (“b”, 13), (“c”, 12), (“d”, 16), (“e”, 9), (“f”, 5)). Our objective is to construct a list of (S, C) Tuples, where C is the Huffman code word for the symbol S.