3.6 Exercise answers (เฉลยแบบฝึกหัด)

Answer 3.1

——————————————————————————————

3

cases จะถูกตรวจสอบตามลำดับที่ปรากฏ:

  • case แรกไม่ match เพราะ Cons ชั้นในสุดใน pattern ต้องการค่า 4 แต่ value ที่กำลังถูก match มีค่า 3 อยู่ที่ตำแหน่งนั้น

  • case ที่สองไม่ match เพราะลิสต์ห้าสมาชิกของเราเริ่มต้นด้วยค่า Cons ไม่ใช่ Nil

  • case ที่สามผูก 1 เข้ากับ x และ 2 เข้ากับ y , match ค่า 3 และ 4 แล้วทิ้ง Cons(5, Nil) ตัวสุดท้ายด้วย wildcard pattern เนื่องจาก case ที่สาม match แล้ว ด้านขวามือของ case (หลังเครื่องหมาย => ) จึงถูกประเมินด้วย bindings x = 1 และ y = 2 ส่งผลให้ได้ค่า 3

  • สอง cases สุดท้ายไม่ถูกพิจารณาเลย เพราะ case ที่สาม match แล้ว แต่ทั้งคู่ก็จะ match เช่นกัน! ลองทดลอง comment ออกทีละ cases ดู


Answer 3.2

——————————————————————————————

def tail[A](as: List[A]): List[A] = as match
  case Cons(_, tl) => tl
  case Nil => sys.error("tail of empty list")

นิยามนี้เริ่มต้นด้วยการ pattern matching บนลิสต์ที่ส่งเข้ามา ลิสต์ของเราสามารถเป็น Cons constructor หรือ Nil constructor ก็ได้ ในกรณีของ Cons constructor เราใช้ pattern binding _ เพื่อเพิกเฉยต่อ head และผูกชื่อ tl เข้ากับ tail ซึ่งทำให้เราสามารถคืน tl เป็นผลลัพธ์ของ function ได้ ถ้าลิสต์ของเราเป็น Nil แทน เราจะ raise error อีกทางหนึ่ง เราสามารถเลือกให้ tail ของลิสต์ว่างเป็นลิสต์ว่าง—นั่นคือ case Nil => Nil การทำแบบนั้นก็สมเหตุสมผล แต่เสี่ยงต่อการกลบเกลื่อนข้อผิดพลาด เพราะการเรียก tail บนลิสต์ว่างมักเป็น bug ดังนั้นการ fail ทันทีจึงดีกว่า โดยให้ error เกิดขึ้นใกล้กับจุดที่ assumption เรื่องความไม่ว่างผิดพลาด


Answer 3.3

——————————————————————————————

def setHead[A](as: List[A], hd: A): List[A] = as match
  case Cons(_, tl) => Cons(hd, tl)
  case Nil => sys.error("setHead of empty list")

เราใช้เทคนิคเดียวกับนิยามของ tail คือ pattern matching บนลิสต์ input และจัดการกับ data constructor แต่ละตัว เหมือนใน tail ถ้าเราเจอ Cons constructor เราจะเพิกเฉยต่อ head ของมันและผูก tail เข้ากับชื่อ tl จากนั้นคืนค่า Cons ใหม่ โดยส่ง head ใหม่ hd และ tl ที่ผูกไว้แล้ว ถ้าเราเจอ Nil constructor เราจะ error หรือเราอาจเลือกที่จะคืนลิสต์ว่างในกรณีนี้แทนก็ได้


Answer 3.4

——————————————————————————————

def drop[A](as: List[A], n: Int): List[A] =
  if n <= 0 then as
  else as match
    case Cons(_, tl) => drop(tl, n - 1)
    case Nil => Nil

เราตรวจสอบก่อนว่าจำนวนสมาชิกที่ขอให้ drop เป็น 0 หรือน้อยกว่านั้นหรือไม่ ถ้าใช่ก็คืนลิสต์ input ( as ) โดยไม่แก้ไขอะไร ถ้าไม่ เราจะ pattern matching บนลิสต์ ถ้าเราเจอ Cons constructor เราจะทิ้งค่า head แล้วเรียก drop แบบ recursive บน tail โดยลดจำนวนสมาชิกที่จะ drop ลง 1 เพื่อหักลบ head ที่ถูกทิ้งไป ถ้าเราเจอค่า Nil แทน เราก็แค่คืน Nil

เหมือน implementations ของ tail และ setHead เราอาจเลือกที่จะ raise error ถ้าถูกขอให้ drop มากกว่าจำนวนสมาชิกที่มีอยู่ในลิสต์ แต่เราเลือกต่างออกไปใน implementation นี้ เพราะ drop มักถูกใช้ในกรณีที่จำนวนสมาชิกถูกคำนวณมา หากเราตัดสินใจ raise error ผู้เรียกจะต้องตรวจสอบขนาดของลิสต์ก่อนเรียก drop (เช่น drop(as, n min size(as)) ) การออกแบบทั้งสองแบบก็ใช้ได้ เมื่อคุณฝึกเขียน functional libraries ไปเรื่อย ๆ คุณจะพัฒนา instinct สำหรับการตัดสินใจแบบนี้


Answer 3.5

——————————————————————————————

def dropWhile[A](as: List[A], f: A => Boolean): List[A] =
  as match
    case Cons(hd, tl) if f(hd) => dropWhile(tl, f)
    case _ => as

เรา pattern matching บนลิสต์ แต่ cases ของเราครั้งนี้ต่างออกไปเล็กน้อย case แรกของเรา match Cons constructor ที่มี head ผ่าน predicate ที่ส่งเข้ามา เราทำสิ่งนี้ด้วย pattern guard—เงื่อนไขบน pattern ที่เขียนด้วย if <condition> ในกรณีนี้เราผูก hd และ tl เข้ากับ head และ tail ของ Cons constructor และใช้ guard if f(hd) case นี้จะ match ก็ต่อเมื่อ f(hd) ประเมินผลเป็น true ซึ่งในกรณีนั้นเราจะเรียก dropWhile แบบ recursive บน tl ส่วน cases ที่เหลือ—Cons constructor ที่ f(hd) ประเมินผลเป็น false และ Nil constructor—จะ match กับ wildcard case และให้ผลลัพธ์เป็นการคืนลิสต์ input

สังเกตว่าเราไม่จำเป็นต้องใช้ pattern guards ตรงนี้ เราสามารถ match เฉพาะโครงสร้างของลิสต์ input ได้แทน:

def dropWhile[A](as: List[A], f: A => Boolean): List[A] =
  as match
    case Cons(hd, tl) =>
      if f(hd) then dropWhile(tl, f)
      else as
    case Nil => as

ทั้งสองวิธีก็ใช้ได้ดีในตัวอย่างเล็ก ๆ แบบนี้ เป็นเรื่องดีที่จะคุ้นเคยกับทั้งสองวิธี และเลือกวิธีที่อ่านง่ายกว่าสำหรับแต่ละกรณี


Answer 3.6

——————————————————————————————

def init[A](as: List[A]): List[A] = as match
  case Nil => sys.error("init of empty list")
  case Cons(_, Nil) => Nil
  case Cons(hd, tl) => Cons(hd, init(tl))

เรา pattern matching บนลิสต์ input ถ้าเจอ Nil เราจะ error ทันที (เหมือนที่ทำใน tail ) ถ้าเจอ Cons(_, Nil) แทน เราจะรู้ว่านี่คือลิสต์สมาชิกเดียว ซึ่งเราจะทิ้งมันและคืน Nil ไม่เช่นนั้น เราต้องมี Cons(hd, tl) ที่ tl ไม่ว่าง (นั่นคือมันไม่เท่ากับ Nil ไม่อย่างนั้นเราคง match มันไปแล้ว) ดังนั้นเราจึงคำนวณ init ของ tail แล้ว cons hd ของเราลงบนผลลัพธ์

runtime ของ init เป็นสัดส่วนกับความยาวของลิสต์ เพราะเราต้อง traverse ผ่านค่า Cons แต่ละตัว ยิ่งไปกว่านั้น เราต้องสร้างลิสต์ทั้งชุดขึ้นมาใหม่ทั้งหมด เพราะไม่มีการใช้ structural sharing ระหว่างลิสต์ตั้งต้นกับผลลัพธ์ของ init สุดท้าย implementation นี้ใช้ stack frame หนึ่งอันต่อหนึ่งสมาชิกของลิสต์ ทำให้เกิดโอกาสที่จะเกิด stack overflow error สำหรับลิสต์ขนาดใหญ่ เราจะได้เห็นวิธีเขียน recursive functions โดยไม่สะสม stack frames อีกไม่นาน


Answer 3.7

——————————————————————————————

ไม่ได้ เป็นไปไม่ได้ foldRight ทำการ recurse ไปจนสุดลิสต์ก่อนที่จะเรียกใช้ function การ traverse แบบเต็มรูปแบบเกิดขึ้นก่อนที่ function ที่ส่งเข้ามาจะถูกเรียกใช้สักครั้งเดียว เราจะพูดถึง early termination ในบทที่ 5


Answer 3.8

——————————————————————————————

foldRight(List(1, 2, 3), Nil: List[Int], Cons(_, _)) ประเมินผลออกมาเป็น Cons(1, Cons(2, Cons(3, Nil))) จำได้ว่า foldRight(as, acc, f) แทนที่ Nil ด้วย acc และแทนที่ Cons ด้วย f เมื่อเราตั้ง acc เป็น Nil และ f เป็น Cons การแทนที่ทั้งหมดของเรากลายเป็นการทำ identity


Answer 3.9

——————————————————————————————

def length[A](as: List[A]): Int =
  foldRight(as, 0, (_, acc) => acc + 1)

เราเรียก foldRight พร้อม accumulator เริ่มต้นเป็น 0 และ function ที่บวก 1 เข้ากับ accumulator สำหรับแต่ละสมาชิกที่มันเจอ


Answer 3.10

——————————————————————————————

@annotation.tailrec
def foldLeft[A, B](as: List[A], acc: B, f: (B, A) => B): B =
  as match
    case Nil => acc
    case Cons(hd, tl) => foldLeft(tl, f(acc, hd), f)

เรา pattern matching บนลิสต์ที่ส่งเข้ามา: ถ้ามันเป็น Nil เราจะคืนผลลัพธ์ที่สะสมไว้ และถ้ามันเป็น Cons เราจะคำนวณ accumulator ใหม่โดยเรียก f ด้วย accumulator ปัจจุบันและ head ของ Cons cell จากนั้นเรียก foldLeft แบบ recursive โดยส่ง tail และ accumulator ใหม่เข้าไป implementation นี้เป็น tail recursive เพราะไม่มีงานเพิ่มเติมต้องทำหลังจาก recursive call เสร็จสิ้น และเราให้ Scala compiler ตรวจสอบว่ามันเป็น tail recursive จริงโดยการเพิ่ม annotation @annotation.tailrec


Answer 3.11

——————————————————————————————

def sum(ints: List[Int]): Int =
  foldLeft(ints, 0, _ + _)
 
def product(ds: List[Double]): Double =
  foldLeft(ds, 1.0, _ * _)
 
def length[A](as: List[A]): Int =
  foldLeft(as, 0, (acc, _) => acc + 1)

Exercise 3.12

——————————————————————————————

def reverse[A](as: List[A]): List[A] =
  foldLeft(as, Nil: List[A], (acc, a) => Cons(a, acc))

เราใช้ foldLeft โดยมี accumulator เริ่มต้นเป็นลิสต์ว่าง และ Cons(a, acc) เป็น combining function เนื่องจาก foldLeft เดินผ่านสมาชิกจากซ้ายไปขวา ลิสต์ผลลัพธ์จึงถูกสร้างจากขวาไปซ้าย ได้ลิสต์ที่เรียงลำดับกลับด้าน


Answer 3.13

——————————————————————————————

implementation ของ foldRight แบบง่ายและ stack safe จะผ่าน List สองรอบ:

def foldRightViaFoldLeft[A, B](as: List[A], acc: B, f: (A, B) => B): B =
  foldLeft(reverse(as), acc, (b, a) => f(a, b))

อันดับแรกเรา reverse ลิสต์ input จากนั้น foldLeft กับผลลัพธ์ที่ได้ โดยสลับลำดับของ parameters ที่ส่งให้ combining function

อีกเทคนิคหนึ่งที่น่าสนใจในเชิงทฤษฎี และใช้ได้ดีพอ ๆ กันทั้งการเขียน foldRight ด้วย foldLeft และการเขียน foldLeft ด้วย foldRight เคล็ดลับคือการสะสม function B => B แทนที่จะสะสมค่าเดี่ยว ๆ ของ type B ในทั้งสองกรณีเราเริ่มต้นด้วย identity function บน type B เป็น accumulator ตั้งต้น: (b: B) => b เมื่อ implement foldRight ผ่าน foldLeft โดยใช้ accumulator ที่มี type B => B combining function ที่ส่งให้ foldLeft จะมี type เป็น (B => B, A) => (B => B) ซึ่งเป็น function ที่รับสอง arguments; argument แรกเป็น function จาก B ไปยัง B และ argument ที่สองเป็น A ส่วน function นี้จะคืน function ใหม่จาก B ไปยัง B

ฟังดูยากไปหน่อย ลองเขียน types ออกมาดู combining function ของเราจะมีหน้าตาแบบนี้: (g: B => B, a: A) => ???: (B => B) เนื่องจากเราต้องคืน function จาก B ไปยัง B เราจึงคืน anonymous function ได้ เมื่อขยายออกมาเราจะได้ (g: B => B, a: A) => (b: B) => ???: B จากตรงนี้เราสามารถไล่ตาม types ได้; เรามี a: A , b: B , function g: B => B และ function f: (A, B) => B เราสามารถนำ a และ b ไป apply กับ f แล้วนำผลลัพธ์ไป apply กับ g เมื่อประกอบทั้งหมดเข้าด้วยกันเราจะได้ implementation ของเรา:

def foldRightViaFoldLeft[A, B](as: List[A], acc: B, f: (A, B) => B): B =
  foldLeft(as, (b: B) => b, (g, a) => b => g(f(a, b)))(acc)

สังเกตว่าผลลัพธ์ของ foldLeft(as, (b: B) => b, (g, a) => b => g(f(a, b))) ให้ function สุดท้ายเป็น B => B เรานำ acc ตั้งต้นไป apply กับ function นั้นเพื่อให้ได้ผลลัพธ์ B

เราสามารถใช้เคล็ดลับเดียวกันนี้เพื่อ implement foldLeft ในรูปของ foldRight :

def foldLeftViaFoldRight[A, B](as: List[A], acc: B, f: (B, A) => B): B =
  foldRight(as, (b: B) => b, (a, g) => b => g(f(b, a)))(acc)

สังเกตว่าทั้งสอง implementations ที่ซับซ้อนนี้ไม่ stack safe เนื่องจากการประกอบ function (function composition) นั้นไม่ stack safe แต่ละ iteration ผ่าน combining function จะทำให้ accumulator ของเราโตขึ้นด้วย anonymous function เพิ่มอีกหนึ่งตัว ถึงกระนั้น implementations เหล่านี้ก็ชี้ไปยังอะไรบางอย่างที่ลึกกว่านั้น ซึ่งเราจะกลับมาพูดถึงอีกครั้งในบทที่ 10


Answer 3.14

——————————————————————————————

def append[A](xs: List[A], ys: List[A]): List[A] =
  foldRight(xs, ys, Cons(_, _))

จำได้ว่า foldRight แทนที่ Nil ด้วย accumulator ตั้งต้น ดังนั้นเราจึงแทนที่ Nil ในลิสต์แรกด้วยลิสต์ที่สองทั้งชุด


Answer 3.15

——————————————————————————————

def concat[A](l: List[List[A]]): List[A] =
  foldRight(l, Nil: List[A], append)

เรารวมลิสต์ชั้นในแต่ละตัวเข้ากับ List[A] ที่สะสมไว้ โดยใช้ function append ของเราจาก exercise 3.14


Answer 3.16

——————————————————————————————

def incrementEach(l: List[Int]): List[Int] =
  foldRight(l, Nil: List[Int], (i, acc) => Cons(i + 1, acc))

เราใช้ foldRight เพื่อให้เราสร้างลิสต์ผลลัพธ์ในลำดับที่ถูกต้อง ขณะที่ใช้ Cons เป็น combining function ก่อนที่เราจะสร้างค่า Cons เราจะ increment ค่า integer ที่ส่งให้ combining function เสียก่อน


Answer 3.17

——————————————————————————————

def doubleToString(l: List[Double]): List[String] =
  foldRight(l, Nil: List[String], (d, acc) => Cons(d.toString, acc))

เราใช้กลยุทธ์เดียวกับที่ทำใน incrementEach : foldRight ที่ใช้ Cons ใน combining function ข้อแตกต่างเพียงอย่างเดียวคือการเรียก d.toString แทน i + 1


Answer 3.18

——————————————————————————————

def map[A, B](as: List[A], f: A => B): List[B] =
  foldRight(as, Nil: List[B], (a, acc) => Cons(f(a), acc))

เราใช้กลยุทธ์เดิมคือ foldRight โดยมี Cons เป็น combining function เราเพียงแค่แยกโครงสร้างร่วมระหว่าง incrementEach และ doubleToString ออกมา สังเกตว่า implementation ของเราจะ stack safe ก็ต่อเมื่อ foldRight stack safe implementation เริ่มแรกของ foldRight ไม่ได้ stack safe แต่เราแสดงวิธีหนึ่งที่จะทำให้มัน stack safe ได้โดยใช้ reverse และ foldLeft ภายใน


Answer 3.19

——————————————————————————————

def filter[A](as: List[A], f: A => Boolean): List[A] =
  foldRight(as, Nil: List[A], (a, acc) => if f(a) then Cons(a, acc) else acc)

implementation นี้คล้ายกับ map ต่างกันตรงที่เราจะสร้าง Cons cell ใหม่ก็ต่อเมื่อ predicate ผ่านเท่านั้น


Answer 3.20

——————————————————————————————

def flatMap[A, B](as: List[A], f: A => List[B]): List[B] =
  foldRight(as, Nil: List[B], (a, acc) => append(f(a), acc))

ตรงนี้เรา foldRight อีกครั้ง โดยแปลง A ให้เป็น List[B] ก่อน แล้วจึงรวมเข้ากับ List[B] ที่สะสมไว้ หรืออีกทางหนึ่ง เราสามารถใช้ map และ concat :

def flatMap[A, B](as: List[A], f: A => List[B]): List[B] =
  concat(map(as, f))

Answer 3.21

——————————————————————————————

def filter[A](as: List[A], f: A => Boolean): List[A] =
  flatMap(as, a => if f(a) then List(a) else Nil)

Answer 3.22

——————————————————————————————

def addPairwise(a: List[Int], b: List[Int]): List[Int] = (a, b) match
  case (Nil, _) => Nil
  case (_, Nil) => Nil
  case (Cons(h1, t1), Cons(h2, t2)) => Cons(h1 + h2, addPairwise(t1, t2))

เราสร้าง pair จากลิสต์ input ทั้งสองของเราแล้ว pattern matching บนผลลัพธ์ ถ้าลิสต์ input ตัวใดตัวหนึ่งว่าง เราจะคืนลิสต์ว่าง ไม่เช่นนั้น ทั้งคู่เป็น Cons cells เราจึงผูกชื่อเข้ากับ heads ของมัน ( h1 และ h2 ) และ tails ( t1 และ t2 ) จากนั้นสร้าง Cons cell ใหม่ที่ head เป็น h1 + h2 และ tail เป็นผลลัพธ์ของการเรียก addPairwise บน tails implementation นี้ไม่ใช่ tail recursive เพราะผลลัพธ์ของ recursive call ถูกใช้เพื่อสร้าง Cons cell ต่อมา


Answer 3.23

——————————————————————————————

def zipWith[A, B, C](a: List[A], b: List[B], f: (A, B) => C): List[C] =
  (a, b) match
    case (Nil, _) => Nil
    case (_, Nil) => Nil
    case (Cons(h1, t1), Cons(h2, t2)) => Cons(f(h1, h2), zipWith(t1, t2, f))

เราได้ทำ generalization สองอย่างตรงนี้; อย่างแรก เราดึงการดำเนินการ + ออกมาเป็น function ที่ส่งให้ zipWith เป็น parameter และอย่างที่สอง เรายอมให้ types ของลิสต์แต่ละตัวต่างกันได้ ดังนั้นเราจึงต้องใช้ type parameters สามตัว—สองตัวสำหรับลิสต์ input และหนึ่งตัวสำหรับลิสต์ผลลัพธ์ เพื่อทำให้ implementation นี้ stack safe เราสามารถส่งค่าที่สะสมไว้เข้าไปใน recursive call แทนที่จะ recurse ก่อนแล้วค่อยใช้ผลลัพธ์ในการคำนวณถัดไป:

def zipWith[A, B, C](a: List[A], b: List[B], f: (A, B) => C): List[C] =
  @annotation.tailrec
  def loop(a: List[A], b: List[B], acc: List[C]): List[C] =
    (a, b) match
      case (Nil, _) => acc
      case (_, Nil) => acc
      case (Cons(h1, t1), Cons(h2, t2)) => loop(t1, t2, Cons(f(h1, h2), acc))
  reverse(loop(a, b, Nil))

ตรงนี้เราแนะนำ local function loop ซึ่งรับ argument acc เพิ่มเติมที่มี type เป็น List[C] เมื่อเรา recurse เราจะส่ง Cons(f(h1, h2), acc) เป็น accumulator ใหม่ การทำแบบนี้ทำให้ accumulator ของเราเรียงลำดับกลับด้านในตอนท้าย ดังนั้นเราจึง reverse คำตอบก่อนที่จะ return ออกจาก zipWith


Answer 3.24

——————————————————————————————

อันดับแรกเราสร้าง helper function ที่ใช้ตรวจสอบว่าลิสต์ l เริ่มต้นด้วยลิสต์อีกตัว prefix หรือไม่:

@annotation.tailrec
def startsWith[A](l: List[A], prefix: List[A]): Boolean = (l, prefix) match
  case (_, Nil) => true
  case (Cons(h, t), Cons(h2, t2)) if h == h2 => startsWith(t, t2)
  case _ => false

เรา recurse บนโครงสร้างของลิสต์ทั้งสอง ถ้า prefix เป็น Nil แล้ว l ก็เริ่มต้นด้วย prefix อยู่แล้วโดยปริยาย ไม่เช่นนั้นเราจะตรวจสอบว่า head ของ l เท่ากับ head ของ prefix หรือไม่ และถ้าเท่ากันเราจะ recurse บน tails เมื่อใช้ helper function นี้แล้ว เราสามารถ implement hasSubsequence ได้:

@annotation.tailrec
def hasSubsequence[A](sup: List[A], sub: List[A]): Boolean = sup match
  case Nil => sub == Nil
  case _ if startsWith(sup, sub) => true
  case Cons(h,t) => hasSubsequence(t, sub)

เรา pattern matching บนโครงสร้างของ sup ถ้า sup ว่าง เราจะคืน true ถ้า sub ว่างเช่นกัน และคืน false ในกรณีอื่น ถ้า sup ไม่ว่าง เราจะตรวจสอบก่อนว่า sup เริ่มต้นด้วย sub หรือไม่ ถ้าใช่ก็จบ เราคืน true ; ถ้าไม่ใช่ เราจะ recurse บน tail ของเราเพื่อตรวจสอบว่า tail มี sub เป็น subsequence หรือไม่


Answer 3.25

——————————————————————————————

object Tree:
  extension (t: Tree[Int]) def maximum: Int = t match
    case Leaf(n) => n
    case Branch(l, r) => l.maximum.max(r.maximum)

เรานิยาม extension method บน Tree[Int] ไว้ใน companion object ของ Tree และ pattern matching บน data constructors ของ t ถ้าเราอยู่ที่ leaf ค่าสูงสุดก็คือค่าของ leaf นั้นโดยตรง ถ้าเราอยู่ที่ branch เราจะคำนวณค่าสูงสุดของทั้ง branch ซ้ายและขวา แล้วคืนค่าที่มากกว่า สังเกตว่า implementation นี้ไม่ใช่ tail recursive


Answer 3.26

——————————————————————————————

enum Tree[+A]:
  def depth: Int = this match
    case Leaf(_) => 0
    case Branch(l, r) => 1 + (l.depth.max(r.depth))

function นี้ใช้ได้กับต้นไม้ทุกแบบ เราจึงนิยามมันเป็น method บน type Tree เราใช้แนวทาง structural recursion เดียวกับที่ใช้ใน maximum ข้อแตกต่างเพียงอย่างเดียวคือค่าที่ใช้ทางด้านขวามือของ => ในแต่ละ case


Answer 3.27

——————————————————————————————

enum Tree[+A]:
  def map[B](f: A => B): Tree[B] = this match
    case Leaf(a) => Leaf(f(a))
    case Branch(l, r) => Branch(l.map(f), r.map(f))

implementation นี้คล้ายกับ implementation แรกของ map บน List มาก โดยเราใช้ structural recursion และในแต่ละ match เราสร้างค่าใหม่ด้วย data constructor ตัวเดิมที่สอดคล้องกัน สำหรับ List เราแปลง Nil เป็น Nil และ Cons เป็น Cons สำหรับ Tree เราแปลง Leaf แต่ละตัวเป็น Leaf และ Branch แต่ละตัวเป็น Branch โดย apply map แบบ recursive บน branches


Answer 3.28

——————————————————————————————

ก่อนอื่นมานิยาม fold กัน:

enum Tree[+A]:
  def fold[B](f: A => B, g: (B,B) => B): B = this match
    case Leaf(a) => f(a)
    case Branch(l, r) => g(l.fold(f, g), r.fold(f, g))

เรา pattern matching บนโครงสร้างของต้นไม้ ถ้าเราเจอ leaf เราจะแปลงค่าของมันด้วย f: A => B ที่ส่งเข้ามา ถ้าเราเจอ branch เราจะ fold subtree แต่ละตัวของมัน จากนั้นรวมผลลัพธ์ด้วย g: (B, B) => B จากนั้นเราสามารถใช้ fold นี้เพื่อ implement แต่ละ function ที่เราเคย implement ไปก่อนหน้านี้:

enum Tree[+A]:
  def size: Int =
    fold(a => 1, 1 + _ + _)
 
  def depth: Int =
    fold(a => 0, (d1,d2) => 1 + (d1 max d2))
 
  def map[B](f: A => B): Tree[B] =
    fold(a => Leaf(f(a)), Branch(_,_))
 
object Tree:
  extension (t: Tree[Int]) def maximum: Int =
    t.fold(a => a, _ max _)

1 Enumerations ถูกนำเข้ามาใน Scala 3 ใน Scala 2 เราใช้ sealed trait ร่วมกับชุดของ case class และ case object แทน โดยแต่ละ case เป็น subtype ของ trait นั้น ดูหัวข้อ enums เทียบกับ sealed traits ที่ท้ายบทนี้สำหรับข้อมูลเพิ่มเติม

2 Scala สร้าง method def toString: String แบบ default ให้กับ enumerations ซึ่งสะดวกต่อการ debug คุณสามารถเห็นผลลัพธ์ของ implementation toString แบบ default นี้ได้ถ้าลองเล่นกับค่า List ใน REPL ซึ่งใช้ toString เพื่อแสดงผลลัพธ์ของแต่ละ expression ตัวอย่างเช่น List.Cons(1, List.Nil) จะถูกพิมพ์ออกมาเป็น string "Cons(1, Nil)" แต่สังเกตว่า toString ที่สร้างออกมาจะเป็นแบบ naive recursive และจะทำให้เกิด stack overflow เมื่อพิมพ์ลิสต์ยาว ๆ ดังนั้นคุณอาจต้องการ implement ขึ้นมาใหม่เอง

3 เราจะเรียก x และ xs เป็นอะไรก็ได้ตรงนั้น แต่ธรรมเนียมทั่วไปคือการใช้ xs , ys , as หรือ bs เป็นชื่อตัวแปรสำหรับลำดับบางอย่าง และใช้ x , y , a หรือ b เป็นชื่อสำหรับสมาชิกตัวเดียวของลำดับ ธรรมเนียมการตั้งชื่ออีกแบบที่พบบ่อยคือ h หรือ hd สำหรับสมาชิกตัวแรกของลิสต์ ( head ของลิสต์), t หรือ tl สำหรับสมาชิกที่เหลือ ( tail ) และ l สำหรับลิสต์ทั้งชุด

4 variable pattern _ ถูกจัดการค่อนข้างพิเศษตรงที่มันสามารถถูกอ้างถึงหลายครั้งใน pattern เพื่อเพิกเฉยต่อหลายส่วนของ target

5 Scala มักจะสามารถตรวจสอบได้ในเวลา compile ว่า match expression ครอบคลุมทุก cases หรือไม่ ในกรณีที่ไม่ครอบคลุม compiler จะรายงาน warning

6 การคัดลอกแบบมองโลกในแง่ร้าย (pessimistic copying) อาจกลายเป็นปัญหาในโปรแกรมขนาดใหญ่ เมื่อข้อมูลที่ mutable ถูกส่งผ่านห่วงโซ่ของ components ที่ผูกกันแบบหลวม ๆ แต่ละ component จำเป็นต้องคัดลอกข้อมูลของตัวเอง เพราะ components อื่นอาจแก้ไขมันได้ ส่วนข้อมูลที่ immutable นั้นปลอดภัยที่จะแชร์เสมอ เราจึงไม่ต้องคัดลอกเลย เราพบว่าในภาพรวม FP มักจะบรรลุประสิทธิภาพที่มากกว่าวิธีการที่พึ่งพา side effects ได้บ่อยครั้ง เนื่องจากการแชร์ข้อมูลและการคำนวณที่มากกว่ามาก

7 ใน Scala standard library foldRight เป็น method บน List และ arguments ของมันถูก curried ทำให้มีรูปแบบการใช้งานเช่น as.foldRight(acc)(f) การ infer types ใน Scala 2 ทำงานกับ parameter lists แต่ละชุดของ function ตามลำดับ—หมายความว่า type ของ acc จะถูก infer ก่อนแล้วจึงจำกัด type ของ f ใน Scala 3 การ infer types ไม่ได้ถูกจำกัดแบบนั้น ดังนั้นแรงจูงใจในการนิยาม parameter lists หลายชุดจึงน้อยลง อย่างไรก็ตาม การนิยาม higher-order functions ให้รับ function argument ตัวสุดท้ายเป็น parameter list ที่แยกต่างหากยังคงให้ข้อดีทาง syntax เพราะทำให้เขียน syntax แบบ as.foldRight(acc): a => ... หรือ as.foldRight(acc) { a => ... } ได้

8 type annotation Nil: List[Int] จำเป็นต้องมีตรงนี้ เพราะไม่อย่างนั้น Scala จะ infer type parameter B ใน foldRight เป็น List[Nothing]

9 เช่นเดียวกัน foldLeft ถูกนิยามเป็น method ของ List ใน Scala standard library และถูก curried ในลักษณะเดียวกันเพื่อการ infer types ที่ดีขึ้น คุณจึงเขียน mylist.foldLeft(0.0)(_ + _) ได้

10 ใน standard library map เป็น method บน List

11 ใน standard library flatMap เป็น method บน List

12 ใน Scala methods ทั้งหมดที่มีชื่อลงท้ายด้วย : จะเป็นแบบ right associative กล่าวคือ expression x :: xs แท้จริงแล้วคือ method call xs.::(x) ซึ่งในทางกลับกันก็เรียก data constructor ::(x,xs) ดูรายละเอียดเพิ่มเติมได้จาก Scala language specification

13 การตั้งชื่อนี้ไม่ใช่เรื่องบังเอิญ มีความเชื่อมโยงที่ลึกซึ้ง—เกินขอบเขตของหนังสือเล่มนี้—ระหว่าง "การบวก" และ "การคูณ" ของ types ในการสร้าง ADT กับการบวกและการคูณของตัวเลข

14 โดยทั่วไปเราจะใช้รูปแบบ syntax แบบ object-oriented นี้เมื่อเป็นไปได้ สำหรับ functions ที่มี operand หลักตัวเดียว (เช่น firstPositive ซึ่งทำงานบน target Tree[Int] หรือ map ซึ่งทำงานบน target Tree[A] ) และใช้รูปแบบ standalone function ในกรณีอื่น

15 ใน Scala เรายังสามารถเปิดเผย patterns เช่น Nil และ Cons โดยไม่ขึ้นกับ data constructors จริงของ type ได้ด้วย