好的,所以我对Haskell非常陌生,而且我知道有很多关于这个东西的信息但是我不理解它。如果有人可以帮助解释并向我展示我做错的事情,那将非常感激,
这里有一些代码:
n = 8 -- number of ingredients (excluding cream)
type Recipe = [Integer] -- some ingredients
-- list all recipes with k of n ingredients
choose :: Integer -> Integer -> [Recipe]
choose n k
| k == 0 = [[]] -- only recipe with no ingredients
| n == k = [[1..n]] -- only recipe with all ingredients
| otherwise = choose (n-1) k ++ map (++ [n])(reverse (choose (n-1) (k-1)))
-- omlette legality (rules must hold conjunctively)
legal r = head $ map (\rule -> False) ruleset
ruleset = [rule0, rule1, rule2, rule3, rule4, rule5, rule6, rule7]
-- Rule 0: If truffles, then precisely truffles.
rule0 r = False
-- Rule 1: Either truffles, garlic, cream, or precisely one meat.
rule1 r = False
-- Rule 2: Not both peppers and onions.
rule2 r = False
以下是成分
bacon = elem 1
peppers = elem 2
ham = elem 3
mushrooms = elem 4
sausage = elem 5
onions = elem 6
garlic = elem 7
truffles = elem 8
cream = elem 9
现在我试图改变规则,使它们满足注释要求,基本上搜索成分列表,
我尝试了一些东西r = if any ( 5== ) Recipe
但很明显它没有用,有人可以详细说明我做错了吗
答案 0 :(得分:2)
不要使用数字,而是使用您自己的数据类型,例如
data Ingredient = Bacon
| Peppers
| Ham
| Mushrooms
| Sausage
| Onions
| Garlic
| Truffles
| Cream
deriving (Eq, Ord, Bounded, Enum)
您可以使用enumFromTo
然后你可以写像
这样的东西rule2 receipt = not ((Peppers `elem` receipt) && (Onions `elem` receipt))
您可以使用
测试是否所有规则都适用legal receipt = all ($ receipt) ruleset