``````Live Demo
add :: Integer -> Integer -> Integer   --function declaration
add x y =  x + y                       --function definition

main = do
putStrLn "The addition of the two numbers is:"
print(add 2 5)    --calling a function
``````

``````The addition of the two numbers is:
7
``````

#### 1. 模式匹配

``````fact :: Int -> Int
fact 0 = 1
fact n = n * fact ( n - 1 )

main = do
putStrLn "The factorial of 5 is:"
print (fact 5)
``````

``````The factorial of 5 is:
120
``````

#### 2. Guards

Guards是一個與模式匹配非常相似的概念。在模式匹配中，通常匹配一個或多個表示式，但是使用`Guards`來測試表示式的某些屬性。

``````fact :: Integer -> Integer
fact n | n == 0 = 1
| n /= 0 = n * fact (n-1)
main = do
putStrLn "The factorial of 5 is:"
print (fact 5)
``````

``````The factorial of 5 is:
120
``````

#### 3. Where字句

`where`關鍵字或內建函式，可在執行時用於生成所需的輸出。當函式計算變得複雜時，這將非常有用。

``````roots :: (Float, Float, Float) -> (Float, Float)
roots (a,b,c) = (x1, x2) where
x1 = e + sqrt d / (2 * a)
x2 = e - sqrt d / (2 * a)
d = b * b - 4 * a * c
e = - b / (2 * a)
main = do
putStrLn "The roots of our Polynomial equation are:"
print (roots(1,-8,6))
``````

``````The roots of our Polynomial equation are:
(7.1622777,0.8377223)
``````

#### 4. 遞回函式

``````Live Demo
fact :: Int -> Int
fact 0 = 1
fact n = n * fact ( n - 1 )

main = do
putStrLn "The factorial of 5 is:"
print (fact 5)
``````

``````The factorial of 5 is:
120
``````

#### 4. 高階函式

``````import Data.Char
import Prelude hiding (map)

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map func (x : abc) = func x : map func abc
main = print \$ map toUpper "tw511.com"
``````

``````sh-4.3\$ ghc -O2 --make *.hs -o main -threaded -rtsopts
sh-4.3\$ main
"TW511.COM"
``````

#### 5. Lambda表示式

``````main = do
putStrLn "The successor of 4 is:"
print ((\x -> x + 1) 4)
``````

``````sh-4.3\$ main
The successor of 4 is:
5
``````