search :: Ord a => a -> [a] -> [a] search _ [] = [] search a xs | m < a = search a behind | m > a = search a front | otherwise = search a front ++ [m] ++ search a behind where (front, m : behind) = splitAt (length xs `div` 2) xs
nameidx :: Name -> [Name] -> Int nameidx n ns = fromJust $ elemIndex n ns
path' :: [[Distance]] -> [Name] -> Name -> Name -> Weight path' dis ns s t = path dis ns !! (nameidx s ns) !! (nameidx t ns)
6.7.2
1 2 3 4 5
steps' :: Int -> RouteMap -> RouteMap steps'1 route = route steps' n route | even n = step t t | odd n = step route (step t t) where t = steps' (n `div` 2) route
foldl :: (b -> a -> b) -> b -> [a] -> b foldr :: (a -> b -> b) -> b -> [a] -> b foldl const :: b -> [a] -> b
-- const 的类型是 a -> b -> a,foldr 的第一个参数的类型要求是 a -> b -> b,导致 a 和 b 的类型必须相同 foldr const :: a -> [a] -> a ------------------------------- map :: (a -> b) -> [a] -> [b]
-- 令 a = a' -> b', b = [a] -> [b] 并代入 [a] -> [b] map map :: [a' -> b'] -> [[a] -> [b]]
-- 看作 (a -> b) -> ([a] -> [b]) 复合 ([a] -> [b]) -> ([[a]] -> [[b]]) map.map :: (a -> b) -> [[a]] -> [[b]] ------------------------------- (.) :: (b -> c) -> (a -> b) -> a -> c
-- 令 b = b' -> c', c = (a' -> b') -> a' -> c' 并代入 (a -> b) -> a -> c (.) (.) :: (a -> b' -> c') -> a -> (a' -> b') -> a' -> c'
-- 看作 (b -> c) -> ((a -> b) -> (a -> c)) 复合 ((a -> b) -> (a -> c)) -> ((a' -> a -> b) -> a' -> (a -> c)) (.).(.) :: (b -> c) -> (a' -> a -> b) -> a' -> a -> c
Chapter 8
8.7.1
1 2 3
brace :: Int -> [String] brace0 = [""] brace n = ["(" ++ x ++ ")" ++ y | c <- [0 .. n - 1], x <- brace c, y <- brace (n - 1 - c)]
encode :: [(Char, [Char])] -> Char -> String encode x c | Just s <- v = snd s where v = find ((== c) . fst) x compress :: String -> String compress s = concatMap (encode (huffman $ freq s)) s
8.8.2 (skip)
姑且跳过
8.9.* (skip)
Chapter 9
9.2.3
1 2 3 4 5 6 7 8
dataTree a = Leaf a | Branch (Tree (a, a)) derivingShow instanceFunctorTreewhere fmap f (Leaf a) = Leaf (f a) fmap f (Branch t) = Branch (fmap (\(x, y) -> (f x, f y)) t) -- test code tree = fmap (+1) (Branch (Branch (Leaf ((1, 2), (3, 4)))))