2013年10月15日火曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の10章(章全部で復習), 10.3(練習問題)、シャッフル(再帰、ラッパーメソッド無し)をHaskellで解いてみる。

その他参考書籍

シャッフル(ラッパー関数無し)

コード(BBEdit)

sample.hs

{-# OPTIONS -Wall -Werror #-}

import qualified System.Random as Random

main :: IO ()
main = do
    let langs = ["ruby", "python", "dart", "haskell", "c", 
                 "scheme", "lisp", "csharp", "cpp", "perl"]
        sorted_langs = sort langs
        shuffled_langs = shuffle sorted_langs
    putStrLn $ "ソート前:    " ++ (show $ langs)
    putStrLn $ "ソート後:    " ++ (show $ sorted_langs)
    putStrLn $ "シャッフル後: " ++ (show $ shuffled_langs)

sort :: [String] -> [String]
sort [] = []
sort xs =
    let myMin :: [String] -> String
        myMin [] = []
        myMin (y:[]) = y
        myMin (y:z:ys) = if y < z
                         then myMin (y:ys)
                         else myMin (z:ys)
        remove :: [String] -> String -> [String]
        remove (v:vs) w = if v == w
                          then vs
                          else v:remove vs w
        remove _ _ = []
        
        a = myMin xs
    in a:(sort $ remove xs a)

shuffle :: [String] -> [String]
shuffle [] = []
shuffle xs = 
    let a = length xs
        r = fst $ Random.randomR (0, a - 1) (Random.mkStdGen 0)
    in (xs !! r):(shuffle $ (take r xs) ++ (drop (r + 1) xs))

入出力結果(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"]
シャッフル後: ["lisp","scheme","perl","c","ruby","cpp","dart","python","haskell","csharp"]
$

0 コメント:

コメントを投稿