如何在Haskell中搜索整数列表
好吧,我对Haskell非常陌生,我知道这方面有很多信息,但我就是不明白。如果有人能帮我解释并告诉我我做错了什么,我将不胜感激 下面是一些代码:如何在Haskell中搜索整数列表,haskell,Haskell,好吧,我对Haskell非常陌生,我知道这方面有很多信息,但我就是不明白。如果有人能帮我解释并告诉我我做错了什么,我将不胜感激 下面是一些代码: n = 8 -- number of ingredients (excluding cream) type Recipe = [Integer] -- some ingredients -- list all recipes with k of n ingredients choose :: Integ
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
但是很明显,它不起作用,有人能详细说明我做错了什么吗
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
你的问题有点分散,很难理解。您能否提供一个简单的示例,说明您希望如何处理预期的输出和遇到的任何编译器错误?另外,您可能在寻找类似于
any(=5)[1,2,3,4,5]
的东西,它可以编译,但是if any(5==)Recipe
的语法不正确,因为if
必须有然后和其他,并且Recipe
是一个类型,而不是一个值。它看起来像是“规则”应该是配方上的谓词(即,类型为Recipe->Bool
)。例如,您可以将规则2(此配方不含辣椒和洋葱)编写为\r->not(pepper`elem`r&&onion`elem`r)
。这就是你要找的吗?尚不清楚“法律”应该做什么;注释是指规则的连接,但是你的代码没有这样做。对不起,让我来解决我的问题,我的老师给了我代码,应该是坏代码。它可以编译和运行,但不能正常运行。现在有很多被评论的“规则”,这些规则基本上是返回一个bool,例如:“如果是块菌,那么就是块菌”,我试图搜索每个食谱列表,看看它是否遵守规则。。如果有道理的话。。