H-99: Ninety-Nine Haskell Problems 2017-4-7
首先附上地址: 99 questions/1 to 10 - HaskellWiki
说明:问题的答案只代表我自己的思路,如果你有更好的解决方法,请告诉我。
Problem 1
序列最后一个元素 Ex: [1,2,3,4] -> 4
myLast :: [a] -> a
myLast [] = error "Empty List"
myLast [x] = x
myLast (_:xs) = myLast xs
Problem 2
序列倒数第二个元素 Ex: [1,2,3,4] -> 3
myButLast :: [a] -> a
myButLast [] = error "Empty List"
myButLast [x] = error "Only One Element"
myButLast [x,_] = x
myButLast (_:xs) = myButLast xs
Problem 3
序列的第k个元素 Ex: elementAt [1,2,3] 2 -> 2
elementAt :: [a] -> Int -> a
elementAt xs n = xs !! (n-1)
Problem 4
序列的长度 Ex: [1,2,3,4] -> 4
myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + myLength xs
Problem 5
反转序列 Ex: [1,2,3] -> [3,2,1]
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = (reverse xs) ++ [x]
Problem 6
判断是否是一个回文序列 Ex: isPalindrome [1,2,3] -> False; isPalindrome "madamimadam" -> True; isPalindrome [1,2,4,8,16,8,4,2,1] -> True
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = if (length xs) `mod` 2 == 0
then False
else xs == reverse xs
网友评论