Haskell函数:: [Name]-> [[((名字,布尔)]] [英] Haskell function :: [Name] -> [[(Name, Bool)]]

查看:56
本文介绍了Haskell函数:: [Name]-> [[((名字,布尔)]]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下内容:

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

我必须实现'envs',以便在给定名称列表的情况下,它返回名称和布尔值的所有可能组合

I have to implement 'envs' so that given a list of Names, it returns all possible combinations of Names and booleans

我的尝试并未返回所有可能的组合,这是我的代码:

My attempt didn't return all possible combinations, this was my code:

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

envs ["P", "Q"]

是:

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

但是,我的是:

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

那么"envs"函数的正确实现是什么,它可以返回预期的结果?

So what is the proper implementation of the 'envs' function, the one that returns the expected result?

推荐答案

您要做的就是获取TrueFalse的所有组合来获取名称的数量,这可以通过专门使用replicateM轻松完成.到列表:

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:

replicateM (length names) [False, True]

例如如果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]
  ]

对于envs ["P", "Q"],这将产生:

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

它适用于任意数量的输入,甚至0,由于与[]不匹配,您的原始实现可能会失败.它总是返回2 n 个分配:

And it works for any number of inputs, even 0, for which your original implementation would fail since you don’t match []. It always returns 2n assignments:

-- 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)]
  ]

这篇关于Haskell函数:: [Name]-&gt; [[((名字,布尔)]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆