開発環境
- 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.2(通過儀礼としてのソート)、再帰をHaskellで解いてみる。
その他参考書籍
- プログラミングHaskell (オーム社) Graham Hutton(著) 山本 和彦(翻訳)
- Real World Haskell―実戦で学ぶ関数型言語プログラミング (オライリージャパン) Bryan O'Sullivan John Goerzen Don Stewart(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
通過儀礼としてのソート(再帰)
コード(BBEdit)
sample.hs
{-# OPTIONS -Wall -Werror #-}
main :: IO ()
main = do
let langs = ["ruby", "python", "dart", "haskell", "c",
"scheme", "lisp", "csharp", "cpp", "perl"]
putStrLn $ "ソート前: " ++ (show $ langs)
putStrLn $ "ソート後: " ++ (show $ sort langs)
sort :: [String] -> [String]
sort xs = recursiveSort xs []
recursiveSort :: [String] -> [String] -> [String]
recursiveSort [] x = x
recursiveSort xs ys =
let myMax :: [String] -> String
myMax [] = []
myMax (x:[]) = x
myMax (x:y:zs) = if x > y
then myMax (x:zs)
else myMax (y:zs)
remove :: [String] -> String -> [String]
remove (x:ws) v = if x == v
then ws
else x:remove ws v
remove _ _ = []
a = myMax xs
vs = remove xs a
in recursiveSort vs (a:ys)
入出力結果(Terminal, runghc)
$ runghc sample.hs ソート前: ["ruby","python","dart","haskell","c","scheme","lisp","csharp","cpp","perl"] ソート後: ["c","cpp","csharp","dart","haskell","lisp","perl","python","ruby","scheme"] $
0 コメント:
コメントを投稿