数字のリストを取得し、厳密に増加/減少/定数シーケンスが続くかどうかを判断する簡単なプログラム(CCC 2012の2番目の質問)があります。例:Haskell:解析方法の影響を受けて怠惰
1 2 3 4 7 8 => Increasing
5 1 -2 -100 => Decreasing
9 9 9 9 9 9 => Constant
1 2 3 4 5 0 => Nothing
私はこれをコード化したときのスマートな方法によって完全に吹き飛んだ。何らかの理由で、私がstdinに対話形式で数字を入力したときに、私も終了する前に私に答えを与えていました!私はバグだと思ったが、ハスケルの怠け者(私は思う?)がそれ自体を取って、1
、2
、3
、0
を入力した後で、結果がNothing
、それでそれは喜んでそれを出力しました。私は
maybeRead :: (Read a) => String -> Maybe a
maybeRead = fmap fst . listToMaybe . filter (null . dropWhile isSpace . snd) . reads
parse :: (Read a) => [String] -> [a]
parse xs =
let entries = map maybeRead xs
in if all isJust entries
then map fromJust entries
else []
として実装され、parse
は、数値入力を読み取るより安全な方法であることを
let readings = parse $ lines input
へ
let readings = map (read :: (Read a, Num a) => String -> a) $ lines input
を変更したとき
は残念ながら、それはもはやこれを行いません。
なぜですか?
EDIT:その他のコード
-- | Zip together adjacent list elements as pairs in a new list.
zipPairs :: [a] -> [(a, a)]
zipPairs xs = zip (init xs) (tail xs)
-- | Return True if all elements of a given list are equal.
constant :: (Eq a) => [a] -> Bool
constant xs = all (== head xs) (tail xs)
-- | Return the order that the elements of a list are sorted in, if they form
-- a strictly increasing (Just LT), decreasing (Just GT) or constant (Just EQ)
-- sequence. If there is no pattern, return Nothing.
order :: (Ord a) => [a] -> Maybe Ordering
order xs =
let orders = map (\(x, y) -> x `compare` y) (zipPairs xs)
in if constant orders then Just (head orders) else Nothing
、その後main
に私が持っている
let readings = parse $ lines input
putStrLn $ if null readings
then "bad input"
else case order readings of
Just EQ -> "Constant"
Just LT -> "Diving"
Just GT -> "Rising"
Nothing -> "Nothing"
+1;啓示の啓示のために+1)。 – gphilip