2013年12月8日日曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の11章(探索とソート)、11.7(練習問題)、11-4.をHaskellで解いてみる。

その他参考書籍

11.7(練習問題)、11-4.

コード(BBEdit)

Sample.hs

{-# OPTIONS -Wall -Werror #-}

main :: IO ()    
main = do
    putStrLn "バブルソートの過程"
    print l
    mapM_ print $ snd $ bubbleSort1 l
    putStrLn "test"
    mapM_ putStrLn $ map (\(a, b) -> if test b then "True" else a) testList

test :: ([Int], [Int]) -> Bool
test (ns, ms) = if bubbleSort ns == ms then True else False

testList :: [(String, ([Int], [Int]))]
testList = [("empty", ([], [])),
            ("one", ([1], [1])),
            ("two ordered", ([1, 2], [1, 2])),
            ("to reversed", ([2, 1], [1, 2])),
            ("three identical", ([3, 3, 3], [3, 3, 3])),
            ("three split", ([3, 0, 3], [0, 3, 3]))]

bubbleSort :: [Int] -> [Int]
bubbleSort [] = []
bubbleSort ns = f (last ns) (init ns) [] []

f :: Int -> [Int] -> [Int] -> [Int] -> [Int]
f x [] [] ls = ls ++ [x]
f x [] ms ls = f (last ms) (init ms) [] (ls ++ [x])
f x ns ms ls =
    let n = last ns
        ks = init ns
    in if x < n then
           f x ks (n:ms) ls
       else
           f n ks (x:ms) ls

l :: [Int]
l = [6, 5, 4, 3, 7, 1, 2]

-- 過程を出力する用
bubbleSort1 :: [Int] -> ([Int], [[Int]])
bubbleSort1 [] = ([], [])
bubbleSort1 ns = g (last ns) (init ns) [] ([], [])

g :: Int -> [Int] -> [Int] -> ([Int], [[Int]]) -> ([Int], [[Int]])
g x [] [] (ls, xs) = (ls ++ [x], reverse xs)
g x [] ms (ls, xs) = g (last ms) (init ms) [] (ls ++ [x], xs)
g x ns ms (ls, xs) =
    let n = last ns
        ks = init ns
    in if x < n then
           g x ks (n:ms) (ls, (ls ++ ks ++ [x] ++ n:ms):xs)
       else
           g n ks (x:ms) (ls, (ls ++ ks ++ [n] ++ x:ms):xs)

入出力結果(Terminal, runghc)

$ runghc Sample.hs
バブルソートの過程
[6,5,4,3,7,1,2]
[6,5,4,3,7,1,2]
[6,5,4,3,1,7,2]
[6,5,4,1,3,7,2]
[6,5,1,4,3,7,2]
[6,1,5,4,3,7,2]
[1,6,5,4,3,7,2]
[1,6,5,4,3,2,7]
[1,6,5,4,2,3,7]
[1,6,5,2,4,3,7]
[1,6,2,5,4,3,7]
[1,2,6,5,4,3,7]
[1,2,6,5,4,3,7]
[1,2,6,5,3,4,7]
[1,2,6,3,5,4,7]
[1,2,3,6,5,4,7]
[1,2,3,6,5,4,7]
[1,2,3,6,4,5,7]
[1,2,3,4,6,5,7]
[1,2,3,4,6,5,7]
[1,2,3,4,5,6,7]
[1,2,3,4,5,6,7]
test
True
True
True
True
True
True
$

慣れるまでは{-# OPTIONS -Wall -Werror #-}の記述を消さずに細かく型を指定していくことに。

0 コメント:

コメントを投稿