Summary (สรุป)

  • Functional data structures เป็น immutable และถูกดำเนินการด้วย pure functions เท่านั้น

  • Algebraic data types (ADTs) ถูกนิยามผ่านเซตของ data constructors

  • ADTs ถูกแสดงใน Scala ด้วย enumerations หรือลำดับชั้นของ sealed traits (sealed trait hierarchies)

  • Enumerations สามารถรับ type parameters ได้ และ data constructor แต่ละตัวสามารถรับอาร์กิวเมนต์ได้ศูนย์ตัวหรือมากกว่า

  • Singly linked lists ถูกจำลองเป็น ADT ที่มี data constructors สองตัว: Cons(head: A, tail: List[A]) และ Nil

  • Companion objects คือ objects ที่มีชื่อเดียวกันกับ data type และ companion objects สามารถเข้าถึง members แบบ private และ protected ของ companion type ได้

  • Pattern matching ทำให้เรา destructure algebraic data type ได้ ซึ่งช่วยให้เราสามารถตรวจสอบ values ที่ใช้สร้าง algebraic data type นั้นได้

  • Pattern matches สามารถถูกนิยามให้ exhaustive ได้ หมายความว่าหนึ่งใน cases จะถูก match เสมอ pattern match ที่ไม่ exhaustive อาจ throw MatchError และ compiler มักจะเตือนเมื่อมีการนิยาม pattern match ที่ไม่ exhaustive

  • โครงสร้างข้อมูลเชิงฟังก์ชันแบบบริสุทธิ์ใช้หลักการ persistence หรือที่รู้จักกันในชื่อ structural sharing เพื่อหลีกเลี่ยงการคัดลอก (copying) ที่ไม่จำเป็น

  • ด้วย singly linked lists บาง operations สามารถ implement ได้โดยไม่ต้องคัดลอกอะไรเลย เช่น การเพิ่มสมาชิกที่ด้านหน้าของลิสต์ (prepending) ส่วน operations อื่น ๆ ต้องคัดลอกทั้งโครงสร้าง เช่น การต่อสมาชิกที่ท้ายลิสต์ (appending)

  • Algorithms หลายตัวสามารถ implement ด้วย recursion บนโครงสร้างของ algebraic data type โดยมี base case ผูกกับ data constructor หนึ่ง และ recursive cases ผูกกับ data constructors ตัวอื่น ๆ

  • foldRight และ foldLeft ทำให้เราคำนวณผลลัพธ์ค่าเดียวได้ด้วยการเยี่ยมชม (visit) ทุก ๆ ค่าในลิสต์

  • map , filter และ flatMap เป็น higher-order functions ที่คำนวณลิสต์ใหม่จากลิสต์ input

  • Extension methods ทำให้สามารถนิยาม methods สไตล์ object-oriented ให้กับ type ได้ในแบบ ad hoc แยกต่างหากจากการนิยามตัว type