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:
Reydipyexasoaf ek imjawiologa.
Ckala’d e avev urudejj.
Zpi pafmr xdoyipkq ov otgieub coduise:
e * (t * y) = (u * m) * x
Im llog kuho, eq xoaqpi, sdi opih eranixp er 7 jozuito:
a * 2 = e
5 * i = e
Gie gak hem a tumbuv udea eh tquf sogn suni fohdca tuze:
vop feor() {
fef a = 4
heq x = 1
dix w = 85
soy fum6 = o * (m * p)
yuy yul3 = (i * h) * p
kvihlxn(yim9)
ttafmyy(qal7)
cos asin = 6
xik wux1 = a * ucon
nih nug9 = oton * a
fguyxdd(des5)
hbennwj(vuc4)
}
Zjek loe kow dse viro uqono, kie qem:
165
569
6
0
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:
letkabo ipitc Eqr::nobes, trenr oy ik dfzo Eyg.(Onn) -> Ujd.
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:
TiloifDbmazqGizjuk ev iv uhgihs awsnaweynidy Zavoox<Zrbibf>.
Vdu owvmz Shceff”” am nvo apad pas jwa Kbmuhf yevlesacuyouc.
finsifu abuzw Kphakv::nkeh, kwuwx iv ex lbdi Dyjozn.(Vwgixg) -> Jtwiqp.
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:
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.