整数を英語に変換

30分プログラム、その771。anarchy golf - 100にインスパイアされて、整数を英語(one,two,three,...)に変換してみました。

今日のポイントは、

alphaNum n = msum [ lookup n table,
                    do let (x, y) = split n
                       x' <- lookup x table
                       y' <- lookup y table
                       return $ printf "%s %s" x' y'
                  ]

のあたり。 Int -> Maybe Stringをいくつか試してみて、最初にJust _を返してきたやつを採用するためにmsumを使ってます。MonadPlusすごい!

使い方

*Main Data.List> alphaNum 1
Just "one"
*Main Data.List> alphaNum 21
Just "twenty one"

ソースコード

import Control.Monad
import Text.Printf
alphaNum :: Int -> Maybe String

table = [(0, "zero"),
         (1, "one"),
         (2, "two"),
         (3, "three"),
         (4, "four"),
         (5, "five"),
         (6, "six"),
         (7, "seven"),
         (8, "eight"),
         (9, "nine"),
         (10, "ten"),
         (11, "eleven"),
         (12, "twelve"),
         (13, "thirteen"),
         (14, "fourteen"),
         (15, "fifteen"),
         (16, "sixteen"),
         (17, "seventeen"),
         (18, "eighteen"),
         (19, "nineteen"),
         (20, "twenty")
        ]

split :: Int -> (Int, Int)
split n = let m = n `div` 10 * 10 in
          (m, n - m)

alphaNum n = msum [ lookup n table,
                    do let (x, y) = split n
                       x' <- lookup x table
                       y' <- lookup y table
                       return $ printf "%s %s" x' y'
                  ]