開発環境
- 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(著) 山下 伸夫 伊東 勝利 株式会社タイムインターメディア(翻訳)
シャッフル(再帰)
コード(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 xs = recursiveShuffle xs []
recursiveShuffle :: [String] -> [String] -> [String]
recursiveShuffle [] _ = []
recursiveShuffle (x:[]) ys = x:ys
recursiveShuffle xs ys =
let a = length xs
r = fst $ Random.randomR (0, a - 1) (Random.mkStdGen 0)
in recursiveShuffle ((take r xs) ++ (drop (r + 1) xs))
((xs !! r):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"] シャッフル後: ["csharp","haskell","python","dart","cpp","ruby","c","perl","scheme","lisp"] $
0 コメント:
コメントを投稿