計算機科学のブログ

関数型プログラミングの基礎 - ファーストクラス関数 - compare関数、GT、LT、EQ

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT1(関数型プログラミングの基礎)、LESSON 4(ファーストクラス関数)、4.4(練習問題)、Q4-1の解答を求めてみる。

コード

sample.hs

import Data.List
main :: IO ()
main = do
    print $ sortBy compareLastNamesBefore names
    print $ sortBy compareLastNames names


-- 1
names :: [(String, String)]
names = [("Ian", "Curtis"),
        ("Bernard", "Sumner"),
        ("Peter", "Hook"),
        ("Stephen", "Morris"),
        ("Peter", "Morris")]

compareLastNamesBefore :: (Ord a1, Ord a2) => (a2, a1) -> (a2, a1) -> Ordering
compareLastNamesBefore name1 name2 = if lastName1 > lastName2
    then GT
    else if lastName1 < lastName2
        then LT
        else if firstName1 > firstName2
        then GT
        else if firstName1 < firstName2
        then LT
        else EQ
    where firstName1 = fst name1
          lastName1 = snd name1
          firstName2 = fst name2
          lastName2 = snd name2

compareLastNames :: (Ord a, Ord b) => (a, b) -> (a, b) -> Ordering
compareLastNames name1 name2 = 
    let cmp = compare (snd name1) (snd name2)
    in
        if cmp == EQ
        then compare (fst name1) (fst name2)
        else cmp

入出力結果(Terminal, Zsh)

% runghc sample.hs 
[("Ian","Curtis"),("Peter","Hook"),("Peter","Morris"),("Stephen","Morris"),("Bernard","Sumner")]
[("Ian","Curtis"),("Peter","Hook"),("Peter","Morris"),("Stephen","Morris"),("Bernard","Sumner")]
%