2017年3月4日土曜日

開発環境

関数プログラミング入門(Richard Bird (著)、山下伸夫 (翻訳)、オーム社)の第5章(リスト処理の例)、5.1(数を言葉に変換する)、練習問題5.1.1、5.1.2、5.1.3、5.1.4、5.1.5を取り組んでみる。

練習問題5.1.1、5.1.2、5.1.3、5.1.4、5.1.5

コード(Emacs)

-- 5.1.1

convert2 :: Int -> String
convert2 = combine2 . digits2

digits2 :: Int -> (Int, Int)
digits2 n = (n `div` 10, n `mod` 10)

units, teens, tens :: [String]
units = ["one", "two", "three", "four", "five",
         "six", "seven", "eight", "nine"]

teens = ["ten", "eleven", "twelve", "thirteen", "fourteen",
         "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]

tens = ["twenty", "thirty", "forty", "fifty",
        "sixty", "seveenty", "eighty", "ninety"]

combine2 :: (Int, Int) -> String
combine2 (0, u) = units !! (u - 1)
combine2 (1, u) = teens !! u
combine2 (t, 0) = tens !! (t - 2)
combine2 (t, u) = tens !! (t - 2) ++ "-" ++ units !! (u - 1)

convert3 :: Int -> String
convert3 = combine3 . digits3

digits3 :: Int -> (Int, Int)
digits3 n = (n `div` 100, n `mod` 100)

combine3 :: (Int, Int) -> String
combine3 (0, t) = convert2 t
combine3 (h, 0) = units !! (h - 1) ++ " hundred"
combine3 (h, t) = units !! (h - 1) ++ " hundred and " ++ convert2 t

convert6 :: Int -> String
convert6 = combine6 . digits6

digits6 :: Int -> (Int, Int)
digits6 n = (n `div` 1000, n `mod` 1000)

combine6 :: (Int, Int) -> String
combine6 (0, h) = convert3 h ++ "."
combine6 (m, 0) = convert3 m ++ " thousand."
combine6 (m, h) = convert3 m ++ " thousand" ++ link h ++ convert3 h ++ "."

link :: Int -> String
link h = if h < 100 then " and " else " "

convert9 :: Int -> String
convert9 n
  | n == 1000000000 = "one billion."
  | otherwise = combine9 (digits9 n)

digits9 :: Int -> (Int, Int)
digits9 n = (n `div` 1000000, n `mod` 1000000)

combine9 :: (Int, Int) -> String
combine9 (0, m) = convert6 m
combine9 (b, 0) = convert3 b ++ " million."
combine9 (b, m) = convert3 b ++ " million and " ++ convert6 m

main :: IO ()
main = do
  print (convert6 1)
  print (convert6 308888)
  print (convert6 369027)
  print (convert6 369401)
  print (convert9 1)
  print (convert9 308888)
  print (convert9 369027)
  print (convert9 369401)
  print (convert9 999999000)
  print (convert9 369000000)
  print (convert9 369401123)
  print (convert9 1000000000)
  

入出力結果(Terminal, ghci, runghc)

$ runghc sample1.hs
"one."
"three hundred and eight thousand eight hundred and eighty-eight."
"three hundred and sixty-nine thousand and twenty-seven."
"three hundred and sixty-nine thousand four hundred and one."
"one."
"three hundred and eight thousand eight hundred and eighty-eight."
"three hundred and sixty-nine thousand and twenty-seven."
"three hundred and sixty-nine thousand four hundred and one."
"nine hundred and ninety-nine million and nine hundred and ninety-nine thousand."
"three hundred and sixty-nine million."
"three hundred and sixty-nine million and four hundred and one thousand one hundred and twenty-three."
"one billion."
$

0 コメント:

コメントを投稿

Comments on Google+: