15.6 Exercise answers (เฉลยแบบฝึกหัด)
| Answer 15.1 | —————————————————————————————— |
สำหรับทั้ง fromListViaUnfold และ fromLazyListViaUnfold เราเริ่ม unfold ด้วย input เริ่มต้น และในแต่ละ iteration เราทำ pattern match บน state ปัจจุบัน โดยคืน Left ถ้า input ว่าง หรือคืน Right ที่ครอบ head และ tail ถ้าไม่ว่าง เราต้อง map บนผลลัพธ์เพื่อ discard state สุดท้ายของ unfold:
def fromListViaUnfold[O](os: List[O]): Pull[O, Unit] =
unfold(os):
case Nil => Left(Nil)
case hd :: tl => Right((hd, tl))
.map(_ => ())
def fromLazyListViaUnfold[O](os: LazyList[O]): Pull[O, Unit] =
unfold(os):
case LazyList() => Left(LazyList())
case hd #:: tl => Right((hd, tl))
.map(_ => ())
| Answer 15.2 | —————————————————————————————— |
เราปล่อยค่าเริ่มต้น จากนั้นเรียก iterate แบบ recursive โดยใช้ผลลัพธ์ของ f(initial) เป็นค่าเริ่มต้นใหม่:
def iterate[O](initial: O)(f: O => O): Pull[O, Nothing] =
Output(initial) >> iterate(f(initial))(f)
| Answer 15.3 | —————————————————————————————— |
เราจะ implement drop ด้วยฟังก์ชัน recursive ที่ uncons element ทีละตัวแล้ว recurse ไปเรื่อย ๆ จนกว่าจำนวนที่เหลือให้ drop จะถึงศูนย์:
def drop(n: Int): Pull[O, R] =
if n <= 0 then this
else uncons.flatMap:
case Left(r) => Result(r)
case Right((_, tl)) => tl.drop(n - 1)
takeWhile คล้ายกันตรงที่เรา uncons element ก่อนแล้วค่อยตัดสินใจว่าจะ recurse หรือไม่ ถ้า element ที่ uncons ออกมาผ่าน predicate เราจะปล่อยมันแล้วเรียก takeWhile บน tail ถ้า element ที่ uncons ออกมาไม่ผ่าน predicate เราจะคืน element นั้นที่นำหน้า tail อยู่แล้วเป็นผลลัพธ์ของ pull ถ้าเราหมด source แทน เราจะคืนผลลัพธ์:
def takeWhile(f: O => Boolean): Pull[O, Pull[O, R]] =
uncons.flatMap:
case Left(r) => Result(Result(r))
case Right((hd, tl)) =>
if f(hd) then Output(hd) >> tl.takeWhile(f)
else Result(Output(hd) >> tl)
dropWhile คล้ายกับ takeWhile มาก ยกเว้นว่าเราไม่ปล่อย elements ที่ผ่าน predicate:
def dropWhile(f: O => Boolean): Pull[Nothing, Pull[O, R]] =
uncons.flatMap:
case Left(r) => Result(Result(r))
case Right((hd, tl)) =>
if f(hd) then tl.dropWhile(f)
else Result(Output(hd) >> tl)
| Answer 15.4 | —————————————————————————————— |
เราใช้ฟังก์ชัน recursive ที่รับยอดรวมสะสมเป็น argument พร้อมกับ pull ตัวถัดไป เราจะ uncons element ถัดไปจาก pull แล้วรวมมันเข้ากับยอดรวมจนถึงตอนนี้ เราปล่อยยอดรวมใหม่และ recurse โดยส่งยอดรวมใหม่และ tail ของการ uncons ถ้าเราใช้ source pull หมดแทน เราจะคืนผลลัพธ์ของ source pull:
def tally[O2 >: O](using m: Monoid[O2]): Pull[O2, R] =
def go(total: O2, p: Pull[O, R]): Pull[O2, R] =
p.uncons.flatMap:
case Left(r) => Result(r)
case Right((hd, tl)) =>
val newTotal = m.combine(total, hd)
Output(newTotal) >> go(newTotal, tl)
Output(m.empty) >> go(m.empty, this)
| Answer 15.5 | —————————————————————————————— |
เช่นเดียวกับ tally ใน exercise ก่อนหน้า เราใช้ฟังก์ชัน recursive ที่รับ state ปัจจุบันและ pull ตัวถัดไปเป็น arguments โดยแทน state ด้วย immutable queue ของ integers ฟังก์ชันจะ uncons element และเพิ่มมันเข้า queue โดยทำให้แน่ใจว่า queue จะไม่โตเกินขนาดที่กำหนด เราจึงปล่อยค่าเฉลี่ย (mean) ของ queue และ recurse บน tail:
extension [R](self: Pull[Int, R])
def slidingMean(n: Int): Pull[Double, R] =
def go(
window: collection.immutable.Queue[Int],
p: Pull[Int, R]
): Pull[Double, R] =
p.uncons.flatMap:
case Left(r) => Result(r)
case Right((hd, tl)) =>
val newWindow = if window.size < n then window :+ hd
else window.tail :+ hd
val meanOfNewWindow = newWindow.sum / newWindow.size.toDouble
Output(meanOfNewWindow) >> go(newWindow, tl)
go(collection.immutable.Queue.empty, self)
| Answer 15.6 | —————————————————————————————— |
ในแต่ละฟังก์ชันเหล่านี้ accumulator type ที่ถูกส่งให้กับ recursive driver function จะกลายเป็น state type ของ mapAccumulate เราต้อง discard state สุดท้ายโดยการ map บนผลลัพธ์ของ mapAccumulate :
def countViaMapAccumulate: Pull[Int, R] =
Output(0) >> mapAccumulate(0)((s, o) => (s + 1, s + 1)).map(_(1))
def tallyViaMapAccumulate[O2 >: O](using m: Monoid[O2]): Pull[O2, R] =
Output(m.empty) >>
mapAccumulate(m.empty): (s, o) =>
val s2 = m.combine(s, o)
(s2, s2)
.map(_(1))
extension [R](self: Pull[Int, R])
def slidingMeanViaMapAccumulate(n: Int): Pull[Double, R] =
self
.mapAccumulate(Queue.empty[Int]): (window, o) =>
val newWindow = if window.size < n then window :+ o
else window.tail :+ o
val meanOfNewWindow = newWindow.sum / newWindow.size.toDouble
(newWindow, meanOfNewWindow)
.map(_(1))
| Answer 15.7 | —————————————————————————————— |
ทางออกหนึ่งคือการ map ฟังก์ชันที่ให้มาบนแต่ละ element แล้วรวม Booleans ที่ได้ทั้งหมดด้วย logical OR monoid implementation นี้ traverse ทั้ง source แทนที่จะหยุดทันทีที่เจอ element ที่ผ่าน predicate:
def exists[I](f: I => Boolean): Pipe[I, Boolean] =
src => src.map(f).toPull.tally(using Monoid.booleanOr).toStream
เรานิยามเวอร์ชันที่หยุด (halting version) ในรูปของเวอร์ชันที่ไม่หยุด โดยการรวมมันกับ takeThrough และ dropWhile :
def takeThrough[I](f: I => Boolean): Pipe[I, I] =
src => src.toPull.takeWhile(f)
.flatMap(remainder => remainder.take(1)).void.toStream
def dropWhile[I](f: I => Boolean): Pipe[I, I] =
src => src.toPull.dropWhile(f)
.flatMap(remainder => remainder).void.toStream
def existsHalting[I](f: I => Boolean): Pipe[I, Boolean] =
exists(f) andThen takeThrough(!_) andThen dropWhile(!_)
หรืออีกทางหนึ่ง เราสามารถแทนที่ dropWhile(!_) ด้วย last —ฟังก์ชันที่ปล่อยค่าสุดท้ายของ pull:
def last[I](init: I): Pipe[I, I] =
def go(value: I, p: Pull[I, Unit]): Pull[I, Unit] =
p.uncons.flatMap:
case Left(_) => Pull.Output(value)
case Right((hd, tl)) => go(hd, tl)
src => go(init, src.toPull).toStream
def existsHalting[I](f: I => Boolean): Pipe[I, Boolean] =
exists(f) andThen takeThrough(!_) andThen last(false)
| Answer 15.8 | —————————————————————————————— |
ก่อนอื่นมานิยาม Pipe[String, Double] ที่รับ input หนึ่งบรรทัดแล้วแปลงมันเป็น Celsius กัน เราสามารถนิยามมันเป็น pipeline ของ pipes ที่รับผิดชอบอย่างเดียว (single-responsibility pipes) แล้วประกอบพวกมันทั้งหมดเข้าเป็น pipe เดียว:
def trimmed: Pipe[String, String] =
src => src.map(_.trim)
def nonComment: Pipe[String, String] =
src => src.filter(_.charAt(0) != '#')
def asDouble: Pipe[String, Double] =
src => src.flatMap: s =>
s.toDoubleOption match
case Some(d) => Stream(d)
case None => Stream()
def convertToCelsius: Pipe[Double, Double] =
src => src.map(toCelsius)
val conversion: Pipe[String, Double] =
trimmed andThen
nonEmpty andThen
nonComment andThen
asDouble andThen
convertToCelsius
จากนั้นเราใช้ pipe นี้แปลงบรรทัดของ input file และเขียน output ที่แปลงแล้วแต่ละบรรทัดไปยัง output file เราต้องเขียน driver function ใน type IO ; เราเปิดไฟล์นำเข้าและไฟล์ส่งออก แล้วใช้ conversion กับบรรทัดนำเข้า โดยเขียนแต่ละบรรทัดที่แปลงแล้วไปยัง output file:
import java.nio.file.{Files, Paths}
def convert(inputFile: String, outputFile: String): IO[Unit] =
IO:
val source = scala.io.Source.fromFile(inputFile)
try
val writer = Files.newBufferedWriter(Paths.get(outputFile))
try
fromIterator(source.getLines)
.pipe(conversion)
.fold(()): (_, a) =>
writer.write(a.toString)
writer.newLine()
finally writer.close()
finally source.close()
| Answer 15.9 | —————————————————————————————— |
เราใช้ Pull.Eval เพื่อสร้าง Pull[F, Nothing, O] จากนั้น flatMap บนมันด้วย Pull.Output ซึ่งให้ผลลัพธ์เป็น Pull[F, O, Unit] ซึ่งเทียบเท่ากับ Stream[F, O] :
def eval[F[_], O](fo: F[O]): Stream[F, O] =
Pull.Eval(fo).flatMap(Pull.Output(_))
| Answer 15.10 | —————————————————————————————— |
เราสามารถใช้ flatMap ร่วมกับ eval ได้ เนื่องจากเรานิยามสิ่งนี้ภายใน companion ของ Stream และเป็นผลจากที่ Stream เป็น opaque type ทับบน Pull เราจึงต้องระวังที่จะอ้างอิง Stream.flatMap อย่างชัดเจน ไม่ใช่ method flatMap บน Pull :
extension [F[_], O](self: Stream[F, O])
def mapEval[O2](f: O => F[O2]): Stream[F, O2] =
Stream.flatMap(self)(o => Stream.eval(f(o)))
| Answer 15.11 | —————————————————————————————— |
implementations แทบจะเหมือนกัน—เรา Eval(f(init)) แล้ว flatMap ผลลัพธ์ โดยจบการทำงานถ้าผลลัพธ์ส่งสัญญาณการจบ หรือปล่อย element และ recurse ด้วย state ใหม่:
object Pull:
def unfoldEval[F[_], O, R](init: R)(f: R =>
F[Either[R, (O, R)]]): Pull[F, O, R] =
Pull.Eval(f(init)).flatMap:
case Left(r) => Result(r)
case Right((o, r2)) => Output(o) >> unfoldEval(r2)(f)
object Stream:
def unfoldEval[F[_], O, R](init: R)(f: R =>
F[Option[(O, R)]]): Stream[F, O] =
Pull.Eval(f(init)).flatMap:
case None => Stream.empty
case Some((o, r)) => Pull.Output(o) ++ unfoldEval(r)(f)
| Answer 15.12 | —————————————————————————————— |
ก่อนอื่นมาพิจารณาว่า attempt โต้ตอบกับ constructors ที่เข้าถึงได้ (คือ unit และ raiseError ) อย่างไร:
unit(a).attempt == unit(Right(a))
raiseError(t).attempt == unit(Left(t))
มาดูด้วยว่า handleErrorWith โต้ตอบกับแต่ละ constructor อย่างไร:
unit(a).handleErrorWith(h) == unit(a)
raiseError(t).handleErrorWith(h) == h(t)
และต่อไปนี้คือวิธีที่ raiseError โต้ตอบกับ flatMap :
raiseError(t).flatMap(f) == raiseError(t)
เราอาจเรียกร้องที่เข้มงวดขึ้นเกี่ยวกับวิธีจัดการ exceptions ได้ ตัวอย่างเช่น unit ควรจับ exceptions ที่ถูก throw จาก thunk argument ของมันไหม?
unit(throw new Exception) == raiseError(new Exception)
exceptions ควรถูกจับไหมถ้าถูก throw จากฟังก์ชันที่ส่งให้ map และ flatMap ?
fa.map(_ => throw new Exception) == raiseError(new Exception)
fa.flatMap(_ => throw new Exception) == raiseError(new Exception)
ไม่มีคำตอบที่ผิด มีแต่ trade-offs
1 จริง ๆ แล้ว JVM จะปิด InputStream (ซึ่งเป็นสิ่งที่อยู่เบื้องหลัง scala.io.Source ) เมื่อมันถูก garbage collected แต่ไม่มีทางการันตีว่าสิ่งนี้จะเกิดขึ้นอย่างทันเวลา หรือเกิดขึ้นเลย! โดยเฉพาะอย่างยิ่งใน generational garbage collectors ที่ทำ full collections ไม่บ่อยนัก
2 ถ้า argument ของ indexOfSlice ไม่มีอยู่ในรูป subsequence ของ input มันจะคืน -1 ดู API docs สำหรับรายละเอียด หรือลองทดลองกับฟังก์ชันนี้ใน REPL
3 เราเลือกที่จะละ trampolining บางส่วนในบทนี้เพื่อความเรียบง่าย
4 เราอาจนิยาม F เป็น +F[+_] แทนได้ เนื่องจากเราจะใช้ effect types ที่เป็น functors เสมอ (และ functors เป็น covariant โดยธรรมชาติ) การทำเช่นนั้นจะทำให้การนิยาม method ต่าง ๆ ง่ายขึ้น แต่จะต้องให้ effect types ที่เราใช้เป็น covariant ใน type parameter ของพวกมันเอง ในทางปฏิบัติ มันหายากที่ effect types เช่น IO จะนิยาม type parameter แบบ covariant ดังนั้นตรงนี้เราเลือก +F[_] .
5 โดยทั่วไปโค้ดของบทจะนิยาม operations บน Stream แทนที่จะเป็น Pull เว้นแต่ operation นั้นมีประโยชน์เมื่อสร้าง recursive pulls
6 implementation นี้ไม่จับ exceptions ที่ถูก throw จาก handler เอง (คือเมื่อ f(t) throw)
