Codeforces 205A - Little Elephant and Rozdil
205A - Little Elephant and Rozdil
以下のように書いたら、calcに渡すリストのサイズが 1 のときにRUNTIME_ERRORとなりました。
import Data.List calc :: [Int] -> String calc xs | length xs > 1 && a == b = "Still Rozdil" | otherwise = case findIndex (== a) xs of Just n -> show (n+1) Nothing -> error "not found" where [a, b] = take 2 $ sort xs
calcにサイズ 1 のリストを渡すと例外が生成されます。
$ ghci GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude> :l 205a.hs [1 of 1] Compiling Main ( 205a.hs, interpreted ) Ok, modules loaded: Main. *Main> calc [1] "*** Exception: 205a.hs:10:5-29: Irrefutable pattern failed for pattern [a, b]
length xs > 1のチェックにて、リストのサイズが 1 より大きい場合にのみ、aとbを参照しているので、エラーは起きないと思っていましたが、そうではないみたいですね。
以下のようにソートしたリストを保持するように書き直しました。
import Data.List calc :: [Int] -> String calc xs | length xs > 1 && ys!!0 == ys!!1 = "Still Rozdil" | otherwise = case findIndex (== (ys!!0)) xs of Just n -> show (n+1) Nothing -> error "not found" where ys = sort xs main = do s <- getLine t <- getLine putStrLn $ calc $ map (\x -> read x :: Int) $ words t