2013年10月11日金曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の9章(自作メソッドの書き方), 9.5(練習問題)、モダンなローマ数字をHaskellで解いてみる。

その他参考書籍

モダンなローマ数字

コード(BBEdit)

sample.hs

{-# OPTIONS -Wall -Werror #-}

main :: IO ()
main = do
    putStrLn $ romanNumeral 4
    putStrLn $ romanNumeral 9
    mapM_ putStrLn $ map (\x -> (show x) ++ ": " ++  romanNumeral x)
                         [1010..1020]

romanNumeral :: Int -> String
romanNumeral a =
    let numRomanPairs :: [(Int, (Char, Char))]
        numRomanPairs = [(100, ('D', 'C')),
                         (10, ('L', 'X')),
                         (1, ('V', 'I'))]
        
        iter :: Int -> [(Int, (Char, Char))] -> Char -> String -> String
        iter _ [] _ s = s
        iter n ((b,(c,d)):xs) e s =
            let f = div n b
                g = mod n b
                h = replicate (div f 5) c
                i = replicate (mod f 5) d
            in case f of
                    9 -> iter g xs d (s ++ (d:[e]))
                    4 -> iter g xs d (s ++ (d:[c]))
                    _ -> iter g xs d (s ++ h ++ i)         
    in iter (mod a 1000) numRomanPairs 'M' (replicate (div a 1000) 'M')

入出力結果(Terminal, runghc)

$ runghc sample.hs
IV
IX
1010: MX
1011: MXI
1012: MXII
1013: MXIII
1014: MXIV
1015: MXV
1016: MXVI
1017: MXVII
1018: MXVIII
1019: MXIX
1020: MXX
$

0 コメント:

コメントを投稿