Tree In Haskell

มกราคม 27, 2009

ตอนนี้กำลัง ค่อยๆ ไล่อ่าน หนังสือ Real World Haskell ที่ร่วมกันเขียนโดย  Bryan O’Sullivan, Don Stewart, and John Goerzen
หนังสือตีพิมพ์เป็นเล่มขายแล้ว อยากซื้อเก็บเหมือนกัน แต่ก็ไม่เคยซื้อผ่าน amazon ไม่มีพวกบัตรเครติด อะไรเลย ก็เลยยังไม่ซื้อ

หนังสือเล่มนี้ มีให้อ่านออนไลน์ผ่านเว็บ http://book.realworldhaskell.org/ ที่จริง หนังสือเล่มนี้ก่อนตีพิมพ์ ผู้แต่งเขาก็เอาขึ้นเว็บ
ให้อ่าน และก็ให้ comment ในแต่ละ paragraph ได้ในระหว่างแต่ง เพราะฉนั้นถ้าเข้าไปอ่านจะเห็นว่าในแต่ละ paragraph จะมีลิ้ง
ให้ comment ได้

มาว่ากันตามหัวข้อ คือ เขียนโครงสร้างข้อมูลแบบ Tree ด้วย Haskell ซึ่งมันเป็นแบบฝึกหัดอยู่ที่บทที่ 3 ว่าให้สร้าง data type Tree
โดยให้มี variable constructor ตัวเดียว โดยใช้ data type Maybe a เข้าช่วย นั่งทำอยู่นาน กว่าจะทำได้ แล้วก็ได้ออกมาแบบนี้

data Tree  a = Node a (Maybe (Tree a)) (Maybe (Tree a))
                deriving (Show)

ถ้าแบบไม่ใช้ Maybe ตามตัวอย่างในหนังสือจะเป็นแบบนี้ ซึ่งจะมี variable constructor 2 ตัวโดย มี Empty อีกตัว

data Tree  a = Node a (Tree a) (Tree a)
                      | Empty
                deriving (Show)

data type Tree ที่สร้างมาเป็น type แบบ Recursive types จะเห็นว่า pattern ของ variable constructor จะมี
data type Tree อยู่ด้วย ตัวอย่างการเอาไปใช้งานแบบ ไม่ใช้ Maybe จะเป็นแบบนี้

myTree = Node 10 Empty Empty
myTree2 = Node 10 (Node 20 Empty Empty) Empty

ส่วนแบบ Maybe เราไม่จำเป็นต้อง สร้าง Empty ขึ้นมาเพราะเราจะใช้ Nothing ซึ่งเป็น ข้อมูลแบบ Maybe ในการกำหนดค่า
childNode ของ Tree ได้ เช่น

myTree = Node 10 Nothing Nothing

และ ใช้ Just ในการกำหนด childNode ที่ไม่เป็น Nothing

myTree2 = Node 10 (Just (Node 20 Nothing Nothing)) Nothing

จบแค่นี้ครับ ไม่ได้อัพบล็อคตัวเองซะนาน เพราะหัวข้ออื่นๆก็เอาไปอัพที่ *66.com ซะหมดแล้ว

Entry Filed under: haskell. ป้ายกำกับ: , , , , .

2 Comments Add your own

  • 1. phondanai  |  มกราคม 28, 2009 at 5:13 am

    โอ้ว นานจิงๆ

    ตอบกลับ
  • 2. pphetra  |  มกราคม 28, 2009 at 7:46 am

    ผมก็อ่านไปอย่างช้าๆ ได้ถึงบท 5 แล้ว

    ตอบกลับ

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


 

มกราคม 2009
พฤ อา
« ส.ค.   ก.พ. »
 1234
567891011
12131415161718
19202122232425
262728293031  

ความเห็นล่าสุด

etcpe9 on Validate Form ด้วย LiveVa…
BraiN on ประสบการณ์ จับใบดำใบแดง
pphetra on Tree In Haskell
phondanai on Tree In Haskell
ืneogravity on About

Meta

Blogroll

cpe9

Linux

programming