用 Haskell 的 list comprehension 來解某數學愛好者社團的某題目。
執行結果
$ ghc -o solution solution.hs && ./solution
[[D,A,D,B,B,D,C,C,D,C]]
有段時間沒寫 Haskell 了所以寫法可能很糟。
用 Haskell 的 list comprehension 來解某數學愛好者社團的某題目。
$ ghc -o solution solution.hs && ./solution
[[D,A,D,B,B,D,C,C,D,C]]
有段時間沒寫 Haskell 了所以寫法可能很糟。
data Answer = A | B | C | D deriving (Eq, Show) | |
solution :: [[Answer]] | |
solution = | |
[ all_answers | |
| let possible_answers = [A, B, C, D] | |
, a01 <- possible_answers | |
, a02 <- possible_answers | |
, a03 <- possible_answers | |
, a04 <- possible_answers | |
, a05 <- possible_answers | |
, a06 <- possible_answers | |
, a07 <- possible_answers | |
, a08 <- possible_answers | |
, a09 <- possible_answers | |
, a10 <- possible_answers | |
, let all_answers = [a01, a02, a03, a04, a05, a06, a07, a08, a09, a10] | |
-- Condition 1 | |
, length (filter (== A) all_answers) == 1 | |
, length (filter (== B) all_answers) == 2 | |
, length (filter (== C) all_answers) == 3 | |
, length (filter (== D) all_answers) == 4 | |
-- Condition 2 | |
, a02 /= a04 | |
, a02 /= a06 | |
, a02 /= a08 | |
, a04 /= a06 | |
, a04 /= a08 | |
, a06 /= a08 | |
-- Condition 3 | |
, a03 == a06 | |
-- Condition 4 | |
, (length (filter (== a06) all_answers)) | |
> (length (filter (== a08) all_answers)) | |
-- Condition 5 | |
, a05 == a04 | |
-- Condition 6 | |
, a06 == a09 | |
-- Condition 7: 這個條件跟條件一等價,故不列出 | |
-- Condition 8: 這題不構成任何制約條件 | |
-- Condition 9 | |
, a09 /= a02 | |
, a09 /= a05 | |
, a09 /= a07 | |
-- 「當初出題者對於第 9 題的確是希望只有一個答案,即是第 2、5、7 題三項均不同」故增加以下三行 | |
, a02 /= a05 | |
, a02 /= a07 | |
, a05 /= a07 | |
-- Condition 10 | |
, a10 == a08 | |
] | |
main :: IO () | |
main = print solution |