Real World Haskell Chapter 3

色々モチベーションが低くて全然やっていなかったので再入門
そして、いきなり3章


1.リストの中の要素数を数える関数を書きなさい。標準関数lengthと同じ答えになるように。
2.型シグネチャ追加

myLength :: [a] -> Int
myLength []     = 0
myLength (x:xs) = 1 + myLength xs


3.リストの平均値を計算する関数を作りなさい。

listAverage :: [Double] -> Double
listAverage [] = 0.0
listAverage xs = sumList xs / fromIntegral (length xs)
    where sumList (x:xs) = x + sumList xs
          sumList _      = 0.0


4.リストを回文にしなさい。
5.与えたリストが回文であるか判定しなさい。

palindrome :: [a] -> [a]
palindrome (x:xs) = [x] ++ palindrome xs ++ [x]
palindrome _      = []

isPalindrome :: Eq a => [a] -> Bool
isPalindrome (x:xs) = if null xs || x /= last xs
                      then False
                      else isPalindrome (take (length xs - 1) xs)
isPalindrome _      = True


6.リストのリストをサブリストの長さでソートする関数を書きなさい

mysortBy書くべき何だろうけど、hoogle みてしまった。

*Main Data.List> :t sortBy
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
*Main Data.List> :i Ordering
data Ordering = LT | EQ | GT 	-- Defined in GHC.Ordering
instance Bounded Ordering -- Defined in GHC.Enum
instance Enum Ordering -- Defined in GHC.Enum
instance Eq Ordering -- Defined in GHC.Base
instance Ord Ordering -- Defined in GHC.Base
instance Read Ordering -- Defined in GHC.Read
instance Show Ordering -- Defined in GHC.Show
import Data.List

myCompare ::  [a] -> [a] -> Ordering
myCompare xs ys = compare (length xs) (length ys)

sortBySubList :: [[a]] -> [[a]]
sortBySubList xs = sortBy myCompare xs

title = ["Peter Camenzind", "Unterm Rad", "Das Nachtpfauenauge", "Knulp", "Gertrud"]