ローマ数字を求める
1..3999の数字をローマ数字に変換する。
あとでググってみたら、ワンライナーとかすごそうなのが色々あったけど、自分としては今の実装で充分読みやすいと思った。Maybeを使って範囲外はNothingにしたりしてみたけど、このあたり空気は読めてない。
パターンマッチングは粗々こんな感じだろうけど、むしろモナドがでてくるここからがヤマなのだろう。
8/14追記:最初roman n の n mod 10|100|1000が0になるケースのパターンを網羅してなかった。実はそのことは知ってたんだけど、問題ないと思ってたら、roman 1900とかでエラーになったのでrecurなる関数を導入してきちんと漏れのないようにした。
パターンに漏れは禁物なんだな。
module Roman where roman' n one five ten | n == 0 = [] | n == 4 = [one, five] | n == 5 = [five] | n == 9 = [one, ten] | n > 5 = five : ( roman' (n-5) one five ten ) | otherwise = (roman' (n-1) one five ten) ++ [one] roman n | 1 <= n && n < 10 = roman' n 'I' 'V' 'X' | 10 <= n && n < 100 = roman' (div n 10) 'X' 'L' 'C' ++ recur (mod n 10) | 100 <= n && n < 1000 = roman' (div n 100) 'C' 'D' 'M' ++ recur (mod n 100) | 1000 <= n && n < 4000 = roman' (div n 1000) 'M' '-' '-' ++ recur (mod n 1000) where recur n | n == 0 = [] | otherwise = roman n chkroman n | n < 1 = Nothing | n < 4000 = Just $ roman n | otherwise = Nothing
fizzbuzz
とりあえずチュートリアル読みながらの今の時点でのもの。
module Main where import IO fiz' n | n < 1 = Nothing | n > 100 = Nothing | 0 == (mod n 15) = Just "FizBuz" | 0 == (mod n 3) = Just "Fiz" | 0 == (mod n 5) = Just "Buz" | otherwise = Just $ show n fiz 1 = ["1"] fiz n = case (fiz' n) of Just x -> fiz (n-1) ++ [x] main=doimp doimp = do putStr "Enter:" line <- getLine yet <- evalu line if yet then doimp else return () where evalu :: String -> IO Bool evalu l | l == "" = return False | (read l) < 1 = do putStrLn "Too low" ; return True | (read l) > 100 = do putStrLn "Too high" ; return True | otherwise = do putStrLn ( show $ fiz $ read l) ; return True
練習
foldlをどう書いたっけな
list1 = fromhsl [ 1,2,3,4] val = listfoldr (-) 0 list1 main = putStrLn (show val) data List a = Nil | Cons a (List a) fromhsl [] = Nil fromhsl (x:xs) = Cons x (fromhsl xs) tohsl Nil = [] tohsl (Cons x xs) = x : (tohsl xs) llen (Nil) = 0 llen (Cons x xs) = 1 + llen xs listhead (Cons x xs) = x listtail (Cons x Nil) = x listtail (Cons x xs) = listtail xs listfoldr f z (Nil) = z listfoldr f z (Cons x xs) = f x (listfoldr f z xs)
JDK7のドキュメント誤り
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7072711
リリース日に見つけてbug databaseに投稿してたやつが、ようやくacceptされた。
JDKチーム的には、HotSpotがコケるとか、もっと優先度の高いバグがいっぱいあるらしいですが
Martin Fowler:意味的衝突
http://capsctrl.que.jp/kdmsnr/wiki/bliki/?SemanticConflict
前日のに引き続き、bliki訳してみた。
この話、当然といえば当然の内容。