2014/07/23 Haskellその4 Ninety-Nine Haskell Problemsを解く
Problem 1
Find the last element of a list.
Answer:
myLast :: [a] -> a
myLast [x] = x
myLast (_:xs) = myLast xs
Problem 2
Find the last element of a list.
Answer:
myButLast :: [a] -> a
myButLast xs = last $ init xs
Problem 3
Find the K'th element of a list. The first element in the list is number 1.
Answer:
elementAt :: [a] -> Int -> a
elementAt [] _ = error "empty"
elementAt xs n = xs !! (n-1)
Problem 4
Find the number of elements of a list.
Answer:
myLength :: [a] -> Int
myLength [] = 0
myLength (x:xs) = 1 + myLength xs
Problem 5
Reverse a list.
Answer:
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x:xs) = myReverse xs ++ [x]
Problem 6
Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).
Answer:
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = xs == (reverse xs)