2013年10月12日土曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の10章(章全部で復習), 10.2(通過儀礼としてのソート)、再帰をHaskellで解いてみる。

その他参考書籍

通過儀礼としてのソート(再帰)

コード(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 コメント:

コメントを投稿