RWH 第四章

-- 自己写一些安全的列表函数,确保它们不会出错。
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead xs = Just $ head xs

safeTail :: [a] -> Maybe [a]
safeTail [] = Nothing
safeTail xs = Just $ tail xs

safeLast :: [a] -> Maybe a
safeLast [] = Nothing
safeLast xs = Just $ last xs

safeInit :: [a] -> Maybe [a]
safeInit [] = Nothing
safeInit xs = Just $ init xs


map' :: (a -> b) -> [a] -> [b]
map' f (x: xs) = f x : map f xs
map' _ [] = []


asInt_fold :: [Char] -> Int
asInt_fold xs = foldl step 0 xs
    where step x y = x * 10  + (digitToInt y)

-- Prelude下面的函数 concat 将一个列表的列表连接成一个单独的列表
concat' :: [[a]] -> [a]
concat' = foldr step [] 
    where step x y = x ++ y

-- 写出你自己山寨的 takeWhile 函数,首先用显式递归的手法,然后改成 foldr 形式.
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' f (x: xs)
    | f x = x: takeWhile' f xs
    | otherwise = []

takeWhile'' :: (a -> Bool) -> [a] -> [a]
takeWhile'' f = foldr step []
    where step x y
        | f x = x: y
        | otherwise = []

你可能感兴趣的:(RWH 第四章)