简体   繁体   English

Haskell函数:: [Name]-> [[((Name,Bool)]]

[英]Haskell function :: [Name] -> [[(Name, Bool)]]

Given the following: 给定以下内容:

type Name = String
envs :: [Name] -> [[(Name , Bool)]]

I have to implement 'envs' so that given a list of Names, it returns all possible combinations of Names and booleans 我必须实现“ envs”,以便给定名称列表,它返回名称和布尔值的所有可能组合

My attempt didn't return all possible combinations, this was my code: 我的尝试并未返回所有可能的组合,这是我的代码:

envs xxs@(x:xs) = [[ (name, value) | name <- xxs  , value <- [False, True] ]]

the expected results for 的预期结果

envs ["P", "Q"]

are: 是:

[ [ ("P",False)
  , ("Q",False)
  ]
, [ ("P",False)
  , ("Q",True)
  ]
, [ ("P",True)
  , ("Q",False)
  ]
, [ ("P",True)
  , ("Q",True)
  ]
]

But, mine were: 但是,我的是:

[[("P",True),("Q",True)],[("P",False),("Q",False)]]

So what is the proper implementation of the 'envs' function, the one that returns the expected result? 那么,“ envs”函数的正确实现是什么,即返回预期结果的函数呢?

What you want to do is get all combinations of True and False for the number of names, which can be done easily with replicateM specialised to lists: 你想要做的就是让所有的组合TrueFalse了名的数量,它可以很容易地做到replicateM专门到列表:

replicateM (length names) [False, True]

Eg if length names == 2 , then this produces: 例如,如果length names == 2 ,则产生:

[ [False, False]
, [False, True]
, [True, False]
, [True, True]
]

What remains is just to zip each of these with the names themselves: 剩下的只是用名称本身来压缩每个名称:

envs names =
  [ zip names values
  | let n = length names
  , values <- replicateM n [False, True]
  ]

For envs ["P", "Q"] this produces: 对于envs ["P", "Q"]会产生:

[ [("P", False), ("Q", False)]
, [("P", False), ("Q", True)]
, [("P", True), ("Q", False)]
, [("P", True), ("Q", True)]
]

And it works for any number of inputs, even 0, for which your original implementation would fail since you don't match [] . 它适用于任意数量的输入,甚至0,由于您不匹配[] ,您的原始实现可能会失败。 It always returns 2 n assignments: 它总是返回2 n个分配:

-- 2^0 == 1
envs [] == [[]]

-- 2^3 == 8
envs ["P", "Q", "R"] ==
  [ [("P", False), ("Q", False), ("R", False)]
  , [("P", False), ("Q", False), ("R", True)]
  , [("P", False), ("Q", True), ("R", False)]
  , [("P", False), ("Q", True), ("R", True)]
  , [("P", True), ("Q", False), ("R", False)]
  , [("P", True), ("Q", False), ("R", True)]
  , [("P", True), ("Q", True), ("R", False)]
  , [("P", True), ("Q", True), ("R", True)]
  ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM