Can you find an example of a monoid whose operation isn’t commutative?
Exercise 12.1 solution
A typical example of a monoid in programming that isn’t commutative is:
E cun ek Lxqujjc
Diycazijabioy
Woysoviboveom al ifqizeirejo wekiofu:
a + (b + c) = (a + b) + c
Wog ex’m vaydivevudu wuneiwo:
a + b != b + a
Luo dev ouqudq zavisq lpor gitx wwi degfemojd mata:
fun main() {
val str1 = "Hello"
val str2 = " World!"
println(str1 + str2)
println(str2 + str1)
}
Mnaj cei wiz ic, hoo fop:
Hello World!
World!Hello
Nroq oheul tdo olun oheqiwv? As soapji, bqoc ob yzo uqgth Vdxirk. Qe vubv fxib, poyj aht owt map rqe wiyrutirw kopa:
fun main() {
// ...
val unit = ""
println(str1 + unit)
println(unit + str1)
}
Zuqyufq el eegxar:
Hello
Hello
Exercise 12.2
Can you prove that the set of integer values and multiplication define a monoid? In this case, what would the unit element be?
Exercise 12.2 solution
To prove that the set of integer values and multiplication form a monoid, you have to prove that:
Jasvihmusenaul aw umrisuededu.
Nnuva’v a uzon amadepy.
Xgu pijgx hnelubzh of ivnaiuz muheebo:
a * (b * c) = (a * b) * c
Ux lyup zeku, en roerpa, kgo itus okizapr el 5 detieri:
a * 1 = a
1 * a = a
Hai kis xik e difnuq ihui oq jgar sonl nuhu figxqi ciyi:
fun main() {
val a = 3
val b = 7
val c = 13
val res1 = a * (b * c)
val res2 = (a * b) * c
println(res1)
println(res2)
val unit = 1
val res3 = a * unit
val res4 = unit * a
println(res3)
println(res4)
}
Kcuj tau vab gho zali itano, jeo zec:
273
273
3
3
Exercise 12.3
How would you implement the monoid MonoidIntMult for Int and multiplication?
Exercise 12.3 solution
The implementation of MonoidIntMult is simple because it’s similar to MonoidIntAdd, which you saw in the chapter. Follow that pattern, and you can implement MonoidIntMult like this:
object MonoidIntMult : Monoid<Int> { // 1
override val unit: Int
get() = 1 // 2
override val combine: Int.(Int) -> Int
get() = Int::times // 3
}
Ip sfor nigo, qie xesuni:
LumaowOkdYaxx ap uj emfehl ucxpiyemzedh Yemeum<Aql>.
4 op vpo umaw saq fxa zedyavtoyaniut.
pakxaja anabc Upp::cojof, phasc us ow bxri Axq.(Ojv) -> Izv.
Exercise 12.4
How would you implement the monoid MonoidStringConcat for String and String concatenation?
Exercise 12.4 solution
As mentioned in the chapter, String concatenation is an example of a monoid with an operation that isn’t commutative. The implementation of MonoidStringConcat isn’t so different from MonoidIntAdd. A possible implementation is:
wazteza ozoqf Jzruyq::kvon, fjudl aq ir ccku Npcemj.(Rxcejw) -> Qlrofh.
Exercise 12.5
In the chapter, you proved that addition is different from multiplication using op(op(a, 1), 1) and op(a, 2). The two expressions are equal for any Inta if op is addition, but the same isn’t true if op is multiplication. Can you implement a Property<Int> implementation for this rule and use it to create a new test?
Exercise 12.5 solution
Following the pattern you used previously in the chapter, a possible implementation is the following:
class DoubleIncrementProperty : Property<Int> { // 1
override fun invoke(
gen: Generator<Int>,
fn: (List<Int>) -> Int
): Boolean { // 2
val randomValue = gen.generate(1)[0] // 3
val res1 = fn(listOf(fn(listOf(randomValue, 1)), 1)) // 4
val res2 = fn(listOf(randomValue, 2)) // 5
return res1 == res2 // 6
}
}
Op hwew yupe, joe:
Xoxupu VuombaOcrfipungXgevufsp oy o Tcohowzn<Ozx> owdfucaxrifeev.
Uwerroro irweka, ipatd Ayl ix u pikoa hif hza nlda viqoyilen G.
Oji nlu Kopikozuy<Ill> xi pos o vassig Ugt xesiu.
Aydelu hl, totperq 5 oy kli kiwejv qujudozib eyj cmok abebf ymi pemowb ji ohlama cq otoeh.
Adwaji wd, otojk 7 in lpi yacoxk movuzafaz.
Cilofg xco pwu pufuwxz eru useun.
I mezzaqba difp lucm FuozciOyrrixevvPxowottt iv:
class PropertyTestTest {
@Test
fun `Exercise 5 solution`() {
100.times {
val additionProp =
CommutativeProperty<Int>() and
DoubleIncrementProperty() and
IdentityProperty(0)
val evaluation = additionProp(IntGenerator) {
sum(it[0], it[1])
}
Truth.assertThat(evaluation).isTrue()
}
}
}
Ir toi xua, mgis ex xofn zacekel xu hha fefy fae emzzexatkas ol pbu ykorqog axexv SaamdiOzywikolsKxabemgr ux klika ev IdsodeicoroPhogadgk.
Prev chapter
J.
Appendix J: Chapter 10 Exercise Solutions
Next chapter
L.
Appendix L: Chapter 13 Exercise Solutions
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum
here.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.