-- 写一个函数 lastButOne, 返回列表倒数第二个元素.
lastButOne [] = error "error"
lastButOne (x: []) = error "error"
lastButOne (x: y: []) = x
lastButOne (x: y: ys) = lastButOne $ y: ys
-- 写一个函数,用来计算一个列表元素的个数.出于测试要求,保证其输出的结果和标准函数 length 保持一致.
length' [] = 0
length' (x: xs) = 1 + length' xs
-- 添加函数的类型签名于你的源文件.出于测试要求,再次加载源文件到ghci.
myLength :: [a] -> Int
myLength [] = 0
myLength (x: xs) = 1 + myLength xs
-- 写一个函数,用来计算列表的平均值,即,列表元素的总和除以列表的长度.(你可能需要用到 fromIntegral 函数将列表长度变量从 integer 类型到 float 类型进行转换.)
avg :: (Fractional a) => [a] -> a
avg [] = 0
avg xs = (sum xs) / (fromIntegral $ length xs)
-- 将一个列表变成回文序列,即,他应该读起来完全一样,不管是从前往后还是从后往前.举个例子,考虑一个列表 [1,2,3],你的函数应该返回 [1,2,3,3,2,1].
reverseArray :: [a] -> [a]
reverseArray [] = []
reverseArray xs = xs ++ reverse' xs
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x: xs) = reverse' xs ++ [x]
-- 写一个函数,用来确定他的输入是否是一个回文序列.
isPali :: (Eq a) => [a] -> Bool
isPali [] = True
isPali xs
| reverse' xs == xs = True
| otherwise = False
-- 创造一个函数,用于排序一个包含许多列表的列表,其排序规则基于他的子列表的长度.(你可能要看看 Data.List 模块的 sortBy 函数.)
sortByLength :: (Ord a) => [[a]] -> [[a]]
sortByLength xs = sortBy compareLength xs
where compareLength x y = compare (length x) (length y)
-- 定义一个函数,其用一个分隔符将一个包含许多列表的列表连接在一起.函数类型定义如下:
intersperse' :: a -> [[a]] -> [a]
intersperse' _ [x] = x
intersperse' seq (x: xs) = x ++ [seq] ++ (intersperse' seq xs)
网友评论