- # lucky.hs
- lucky :: Int -> String
- lucky 7 = "LUKCY NUMBER SEVEN!"
- lucky x = "Sorry"
-
- ghci>lucky 3
- "Sorry"
- ghci>lucky 7
- "LUKCY NUMBER SEVEN!"
- # factorial.hs
- factorial :: Int -> Int
- factorial 0 = 1
- factorial n = n * factorial(n - 1)
-
- ghci>factorial(3)
- 6
- # addVectors.hs
- addVectors :: (Double, Double) -> (Double, Double) -> (Double, Double)
- addVectors a b = (fst a + fst b, snd a + snd b)
-
- ghci>addVectors (1, 3) (2, 4)
- (3.0,7.0)
- # first.hs
- first :: (a, b, c) -> a
- first (x, _, _) = x
-
- # second.hs
- second :: (a, b, c) -> b
- second (_, y, _) = y
-
- ghci>first (1, 2, 3)
- 1
- ghci>second (1, 2, 3)
- 2
- # head.hs
- head' :: [a] -> a
- head' [] = error "Can't call head on an empty list"
- head' (x:_) = x
-
- ghci>head' [1, 2, 3]
- 1
- # firstLetter.h
- firstLetter :: String -> String
- firstLetter "" = "Empty string"
- firstLetter all@(x:xs) = "The first letther of " ++ all ++ " is " ++ [x]
-
- ghci>firstLetter "Hello World"
- "The first letther of Hello World is H"
- # bmiTell.hs
- bmiTell :: Double -> String
- bmiTell bmi
- | bmi <= 18.5 = "you're underweight"
- | bmi <= 25.0 = "normal"
- | otherwise = "whale"
-
- ghci>bmiTell 18.5
- "you're underweight"
- ghci>bmiTell 20
- "normal"
- # bmiTell.hs
- bmiTell :: Double -> Double -> String
- bmiTell weight height
- | weight / height ^ 2 <= 18.5 = "you're underweight"
- | weight / height ^ 2 <= 25.0 = "normal"
- | otherwise = "whale"
-
-
- # bmiTell.hs (using where keyword)
- bmiTell :: Double -> Double ->String
- bmiTell weight height
- | bmi <= 18.5 = "you're underweight"
- | bmi <= 25.0 = "normal"
- | otherwise = "whale"
- where bmi = weight / height ^ 2
- calcBmis :: [(Double, Double)] -> [Double]
- calcBmis xs = [bmi w h | (w, h) <- xs]
- where bmi weight height = weight / height ^ 2
- # calcBmis.hs
- calcBmis :: [(Double, Double)] -> [Double]
- calcBmis xs = [bmi w h | (w, h) <- xs]
- where bmi weight height = weight / height ^ 2
-
- ghci> calcBmis [(4, 2)]
- [1.0]
- # cylinder.hs
- cylinder :: Double -> Double -> Double
- cylinder r h =
- let sideArea = 2 * pi * r * h
- topArea = pi * r ^ 2
- in sideArea + 2 * topArea
-
- ghci>cylinder 4 5
- 226.1946710584651
- ghci> [let square x = x * x in (square 5, square 3, square 2)]
- [(25,9,4)]
- ghci> (let a = 100; b = 200; c = 300 in a * b * c, let foo = "Hey "; bar = "there!" in foo ++ bar)
- (6000000,"Hey there!")
- ghci> (let (a, b, c) = (1, 2, 3) in a + b + c) * 100
- 600
- # calcBmis.hs
- calcBmis :: [(Double, Double)] -> [Double]
- calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^2]
- # head.hs
- head' :: [a] -> a
- head' xs = case xs of [] -> error "No head for empty list!"
- (x:_) -> x
-
- ghci> head' "Hello World"
- 'H'
- describeList :: [a] -> String
- describeList ls = "The list is " ++ what ls
- where what [] = "empty."
- what [x] = "a singleton list."
- what xs = "a longer list."