这是之前一些学习haskell过程中做过的题
Q1 把每一个元音字母大写
vTest :: Bool
vTest = (capVowels "mmh" == "mmh") &&
(capVowels "learn" == "lEArn") &&
(capVowels "Only" == "Only") &&
(capVowels "holy" == "hOly")
capVowels :: String -> String
capVowels xs = [if x `elem` "aeiou" then toUpper x else x | x <- xs]
Q2 模拟实现平方根
a*x^2 + b*x + c =0
qrTest :: Bool
qrTest = and (map isQR [
(2, (-8), 8, Just (2.0,2.0)),
(5, 2, 1, Nothing),
(5, 6, 1, Just (-0.2,-1.0)),
(1, (-4), 6.25, Nothing)])
where
isQR (i, j, k, l) = qRoots i j k == l
qRoots :: (Ord z, Floating z) => z -> z -> z -> Maybe (z, z)
qRoots a b c = if d >= 0
then Just (x1,x2)
else Nothing
where
d = b^2 - 4*a*c
x1 = (-b + sqrt d) / (2*a)
x2 = (-b - sqrt d) / (2*a)
Q3 返回两个变量中有几个一样,几个不一样的元素
mTest :: Bool
mTest = (tMatch [1, 2, 3] [2, 2, 3] == Just (2,1)) &&
(tMatch [1, 2, 3] [2, 2, 3, 4] == Nothing) &&
(tMatch "soft2" "soft3" == Just (4,1)) &&
(tMatch "THE2" "SOF3" == Just (0,4)) &&
(tMatch " " " " == Just (1,0))
tMatch :: (Eq a) => [a] -> [a] -> Maybe (Int,Int)
tMatch xs ys = if length xs /= length ys then Nothing
else Just (same,diff)
where
same = length $ filter (\(x,y) -> x == y) $ zip xs ys
diff = length $ filter (\(x,y) -> x /= y) $ zip xs ys
Q4 最长连续次数
例如:abcddddefgaaaabb,最长连续次数=4,贡献者是 a 和 d
maxRepeat :: String -> Int
maxRepeat = maximum . map length . group
Q5 输出所有连续出现次数最多的字母
maxE :: String -> String
maxE s = let n = maximum . map length . group $ s
in [ head xs | xs <- group s, length xs == n]
Q6 第1格放1粒麦子,第2格放2粒,第3格4粒,第4格8粒,每格都加倍
total :: Int -> Integer
total n = sum $ take n (iterate (*2) 1) -- take,取前n个数
Q7 角谷定理
jiao :: Int -> [Int]
jiao 1 = [1]
jiao n
| even n = n : jiao (n `div` 2)
| otherwise = n : jiao (n*3+1)
jiaoLen :: Int -> Int
jiaoLen n = maximum [length (jiao x) | x <- [1..n]] - 1