DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on

3

ความต่างโครงสร้าง type ของ Haskell กับ Elixir

Haskell เป็น static type ส่วน Elixir เป็น dynamic type แต่ไม่ได้เรื่องนี้เท่านั้น ยังมีเรื่องแนวคิดของโครงสร้าง type เรื่องการสร้างค่าของ type (data constructor) อีกที่ต่างกัน

  • Haskell นั้นให้เรากำหนด type ใหม่ขึ้นมาได้ โดยให้เราออกแบบ data constructor เองได้ ว่า data ของ type เป็นแบบไหนได้บ้าง เช่น
data Color = Red | Green | Blue
Enter fullscreen mode Exit fullscreen mode

จะเห็นว่า ออกแบบ data constructor ได้เองเลย ถ้า data type ที่ซับซ้อนกว่านั้นก็อาศัยกลไลของ Sum Type และ Product Type สร้าง data constructor แบบที่ต้องการขึ้นมา

ขอดีคือออกแบบเองได้เลย ข้อเสียคือ ในเมื่อโครงสร้างของ data constructor มันไม่เหมือนกัน ดังนั้นก็ต้องเขียนโค้ดเองเพื่อจัดการ การแสดงผลของ data type

Haskell มี class Show ให้สามารถ derive ได้ก็จริง แต่ก็ไม่ทุกเคสที่จะสามารถ generate code instance Show ให้ได้ อย่าง data Color ข้างบนง่ายๆแบบนั้น ก็ deriving Show แบบนี้ได้เลย

data Color = Red | Green | Blue deriving (Show)
Enter fullscreen mode Exit fullscreen mode

คนใช้งานก็ต้องมานั่งศึกษาเองแต่ละ type ว่าจะสร้างค่ายังไง บาง library ที่ type ซับซ้อน ก็จะมี function builder ช่วยให้อีกที

  • Elixir ส่วนของ Elixir นั้น กำหนดโครงสร้างข้อมูลพื้นฐานมาให้เช่น number, keyword, string, list, map

การสร้าง type ขึ้นมาเองนั้นจริงๆแล้วไม่ได้กำหนดแบบ static แบบ Haskell แต่เป็นการเอา type พื้นฐานมากำหนดโครงสร้าง และมีการใช้ defstruct ที่โครงสร้างด้านในคือ map แต่ว่า compiler จะช่วยเช็ค key sets ให้เพราะ struct เป็นโครงสร้างที่ต้องระบุ key ที่รู้ล่วงหน้า เช่น

defmodule Employee do
  defstruct [:name, :age, :department]
end
Enter fullscreen mode Exit fullscreen mode

ข้อเสียก็คือเราสร้าง static type name เองไม่ได้ แต่ส่วนใหญ่แก้ด้วยการเขียน type spec เพื่อเป็น document และใช้ static analysis tool ช่วยเช็คได้บ้าง

ข้อดีคือข้อมูลมันแสดงผลออกมาได้อยู่แล้วเพราะมันเป็นแค่ ข้อมูลพื้นฐานที่ประกอบกัน และ คนใช้งานก็สามารถสร้างข้อมูลออกมาได้เสมอ ไม่ต้องเรียนรู้แยกไปในแต่ละ type แบบ Haskell

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay