開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- Haskell (純粋関数型プログラミング言語)
- GHC (The Glasgow Haskell Compiler) (処理系)
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の10章(章全部で復習), 10.3(練習問題)、辞書順ソートをHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
辞書順ソート(小文字化(Data.CharモジュールのtoLower関数))
コード(BBEdit)
sample.hs
{-# OPTIONS -Wall -Werror #-} import qualified Data.Char as Char main :: IO () main = do let langs :: [String] langs = ["ruby", "python", "dart", "haskell", "c", "scheme", "lisp", "csharp", "cpp", "perl", "Ruby", "Python", "Dart", "Haskell", "C", "Scheme", "Lisp", "CSharp", "CPP", "Perl"] sorted_langs = sort langs putStrLn $ "ソート前: " ++ (show $ langs) putStrLn $ "ソート後: " ++ (show $ sorted_langs) sort :: [String] -> [String] sort [] = [] sort xs = let myMinString :: [String] -> String myMinString [] = [] myMinString (y:[]) = y myMinString (y:z:ys) = if myMin y z then myMinString (y:ys) else myMinString (z:ys) myMin :: String -> String -> Bool myMin [] _ = True myMin _ [] = False myMin (u:us) (t:ts) | (Char.toLower u) < (Char.toLower t) = True | (Char.toLower u) > (Char.toLower t) = False | otherwise = myMin us ts remove :: [String] -> String -> [String] remove (v:vs) w = if v == w then vs else v:remove vs w remove _ _ = [] a = myMinString xs in a:(sort $ remove xs a)
入出力結果(Terminal, runghc)
$ runghc sample.hs ソート前: ["ruby","python","dart","haskell","c","scheme","lisp","csharp","cpp","perl","Ruby","Python","Dart","Haskell","C","Scheme","Lisp","CSharp","CPP","Perl"] ソート後: ["c","C","cpp","CPP","csharp","CSharp","dart","Dart","haskell","Haskell","lisp","Lisp","perl","Perl","python","Python","ruby","Ruby","scheme","Scheme"] $
0 コメント:
コメントを投稿