factorial :: (Integral a) => a -> afactorial 0 = 1factorial n = n * factorial (n - 1)addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)first :: (a, b, c) -> afirst (x, _, _) = xtell :: (Show a) => [a] -> Stringtell [] = ""tell [x: []] = ""tell [x:y:[]] = ""tell [x:y:_] = "too long, the first is " ++ show x ++ " and the second is " ++ show ylength' :: (Num b) => [a] -> blength' [] = 0length' (_:xs) = 1 + length' xscapital :: String -> Stringcapital "" = ""capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x] # @是as模式
o→ guard
bmiTell :: (RealFloat a) => a -> StringbmiTell weight height | bmi <= skinny = "You're underweight" | bmi <= normal = "You're supposedly normal" | bmi <= fat = "You're fat" | otherwise = "You're a whale" where bmi = weight / height ^ 2 (skinny, normal, fat) = (18.5, 25.0, 30.0) # where是语法结构,不是表达式calcBmis :: (RealFloat a) => [(a, a)] -> [a]calcBmis xs = [bmi w h | (w, h) <- xs, let bmi = w / h ^ 2]myCompare :: (Ord a) => a -> a -> Orderinga `myCompare` b | a > b = GT | a == b = EQ | otherwise = LT
o→ quicksort
quicksort :: (Ord a) => [a] -> [a]quicksort [] = []quicksort (x:xs) = let smallerSorted = quicksort (filter (<=x) xs) biggerSorted = quicksort [a | a <- xs, a > x] in smallerSorted ++ [x] ++ biggerSorted
o→ curry
compareWithHundred :: (Num a, ord a) => a -> OrderingcompareWithHundred = compare 100divideByTen :: (Floating a) => a -> adivideByTen = (/10) # 中缀函数用括号来不完全调用 # 但(-4)表示负4, (substract 4)来表示减4函数
o→ 高阶函数
applyTwice :: (a -> a) -> a -> aapplyTwice f x = f (f x)
o→ lambda
addThree :: (Num a) => a -> a -> a -> aaddThree = \x -> \y -> \z -> x + y + z