วันอาทิตย์ที่ ๓๐ มีนาคม พ.ศ. ๒๕๕๑

GHC ต่อ

อ่านจาก Tutorial Chapter 3

เมื่อเราพิมพ์ expression ของ haskell ที่ prompt GHCi จะทำการ evaluate แล้วให้ผลลัพธ์ทันที เช่น

Prelude> reverse "hello"
"olleh"
Prelude> 5+5
10


ตัว GHCi นอกจาก evaluate expression แล้วยังจัดการเกี่ยวกับ IO ด้วย เช่น



Prelude> putStrLn "hello"
hello


Prelude> do { putStrLn "hello"; return "yes" }
hello
"yes"


Prelude> x <- return 42
42
Prelude> print x
42
Prelude>


statement  x <- return 42 หมายถึง "execute return 42" ใน IO และจากนั้นให้ bind ผลลัพธ์ไปเก็บที่ x หลังจากนั้นเราสามารถใช้ x ใน statment อื่น ต่อได้ทันที เช่น ใช้คำสั่ง print เพื่อแสดงข้อมูลที่ x เก็บไว้ออกมา



 



เราสามารถ bind โดยใช้ let ก็ได้ดังนี้



Prelude> let x = 42
Prelude> x
42
Prelude>


นอกจากนี้เรายังสามารถใช้ let ในการสร้าง function ขึ้นมาใช้งานได้เช่น



Prelude> let add a b = a + b
Prelude> add 1 2
3
Prelude>


Prelude> let extraadd a b = a + a + b

Prelude> extraadd 1 2


4


Prelude>



 



 

0 ความคิดเห็น: