計算機科学のブログ

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

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

コード

import Data.List

names :: [([Char], [Char])]
names = [
    ("Ian", "Curtis"),
    ("Bernard", "Sumner"),
    ("Peter", "Hook"),
    ("Stephen", "Morris"),
    ("Ian", "Curtis"),
    ("Bernard", "Hook")
 ]
compareLastNames :: (Ord b, Ord a) => (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)

% ghci 
GHCi, version 8.10.4: https://www.haskell.org/ghc/  :? for help
macro 'doc' overwrites builtin command.  Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /.../.ghc/ghci.conf
Prelude
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.03 secs,)
*Main
λ> names
[("Ian","Curtis"),("Bernard","Sumner"),("Peter","Hook"),("Stephen","Morris"),("Ian","Curtis"),("Bernard","Hook")]
it :: [([Char], [Char])]
(0.01 secs, 153,032 bytes)
*Main
λ> sortBy compareLastNames names
[("Ian","Curtis"),("Ian","Curtis"),("Bernard","Hook"),("Peter","Hook"),("Stephen","Morris"),("Bernard","Sumner")]
it :: [([Char], [Char])]
(0.04 secs, 149,696 bytes)
*Main
λ> :q
Leaving GHCi.
%