14.5 Exercise answers (เฉลยแบบฝึกหัด)
| Answer 14.1 | —————————————————————————————— |
ลอง fold ไปเหนือสมาชิกของ map โดยใช้ operation write บน STArray เพื่อกำหนดค่าที่แต่ละ index ในการเริ่ม fold เราจะยก (lift) ค่า unit ขึ้นไปใน ST :
def fill(xs: Map[Int, A]): ST[S, Unit] =
xs.foldRight(ST[S, Unit](())):
case ((k, v), st) => st.flatMap(_ => write(k, v))
| Answer 14.2 | —————————————————————————————— |
เราสามารถย้าย (port) คำนิยามดั้งเดิมของ partition มาได้ โดยแทนที่การเข้าถึงและการอัปเดต array แต่ละครั้งด้วย operation ที่เทียบเท่ากันบน STArray คำนิยามดั้งเดิมใช้ var j ซึ่งเราสามารถแทนที่ด้วย STRef :
def partition[S](
a: STArray[S, Int], l: Int, r: Int, pivot: Int
): ST[S, Int] =
for
vp <- a.read(pivot)
_ <- a.swap(pivot, r)
j <- STRef(l)
_ <- (l until r).foldLeft(ST[S, Unit](()))((s, i) =>
for
_ <- s
vi <- a.read(i)
_ <- if vi < vp then
for
vj <- j.read
_ <- a.swap(i, vj)
_ <- j.write(vj + 1)
yield ()
else ST[S, Unit](())
yield ())
x <- j.read
_ <- a.swap(x, r)
yield x
การย้ายคำนิยามดั้งเดิมของ qs มานั้นง่ายกว่า ตรรกะไม่จำเป็นต้องเปลี่ยน การเปลี่ยนแปลงเดียวที่ต้องทำคือคืนค่า ST[S, Unit] ที่เราสร้างขึ้นแทนที่จะเป็น Unit :
def qs[S](a: STArray[S,Int], l: Int, r: Int): ST[S, Unit] =
if l < r then for
pi <- partition(a, l, r, l + (r - l) / 2)
_ <- qs(a, l, pi - 1)
_ <- qs(a, pi + 1, r)
yield () else ST[S, Unit](())
| Answer 14.3 | —————————————————————————————— |
ลองห่อ HashMap[K, B] ด้วยคลาสแบบเดียวกับที่เราทำกับ STArray โดยให้ constructors เป็น method บน companion object ที่ให้ค่าเริ่มต้นของ HashMap จากนั้นเราก็เพิ่ม method ลงในคลาสสำหรับแต่ละ operation ที่เข้าถึงหรือแก้ไข map โดยห่อการเรียกที่ส่งต่อ (delegated call) ไว้ใน ST :
final class STMap[S, K, V] private (private val table: HashMap[K, V]):
def size: ST[S, Int] = ST(table.size)
def apply(k: K): ST[S, V] = ST(table(k))
def get(k: K): ST[S, Option[V]] = ST(table.get(k))
def +=(kv: (K, V)): ST[S, Unit] = ST(table += kv)
def -=(k: K): ST[S, Unit] = ST(table -= k)
object STMap:
def empty[S, K, V]: ST[S, STMap[S, K, V]] =
ST(new STMap(HashMap.empty))
def fromMap[S, K, V](m: Map[K, V]): ST[S, STMap[S, K, V]] =
ST(new STMap((HashMap.newBuilder ++= m).result()))
1 มีต้นทุนด้านประสิทธิภาพและความสะดวกเชิงสัญลักษณ์ (notational convenience) เข้ามาเกี่ยวข้อง ดังนั้นจงมองมันเป็นอีกเทคนิคหนึ่งในชุดเครื่องมือของคุณ ไม่ใช่สิ่งที่ต้องถูกใช้งานทุกครั้งที่คุณใช้ local mutation
2 เราใช้ polymorphic thunk ตรงนี้เพราะ Scala ไม่รองรับ polymorphic values โดยตรง (เช่น [s] => ST[s, A] )
3 ดู chapter notes ( https://github.com/fpinscala/fpinscala/wiki ) สำหรับลิงก์อ่านเพิ่มเติม
