简体   繁体   English

Haskell 列出组合 function

[英]Haskell lists combine function

I want to write a recursive function that gets two lists + a requirement as input and outputs all possible tuples with one element each from the 1st and 2nd list that meet the requirement.我想编写一个递归的 function,它获取两个列表 + 一个要求作为输入,并输出所有可能的元组,其中每个元素来自满足要求的第一个和第二个列表。

It should look something like this:它应该看起来像这样:

combine [1,2,3] [5,6,7] (\ab -> a+b > 7) -> [(1,7),(2,6),(2,7),(3,5),(3,6),(3,7)].组合 [1,2,3] [5,6,7] (\ab -> a+b > 7) -> [(1,7),(2,6),(2,7),(3, 5),(3,6),(3,7)]。

I currently just have:我目前只有:

combine:: [a] -> [b] -> [(a, b)] 
combine [] ys = []
combine xs [] = []
combine (x:xs) (y:ys) = (x,y) : combine xs ys 

but it doesn't filter for anything.但它不会过滤任何东西。

That makes sense, since your input does not filter for anything.这是有道理的,因为您的输入不会过滤任何内容。 You should add an extra parameter here:你应该在这里添加一个额外的参数:

combine:: [a] -> [b] -> (a -> b -> Bool) -> [(a, b)]
combine [] ys _ = []
combine xs [] _ = []
combine (x:xs) (y:ys) p
  | … = …
  | otherwise = …

here p is thus a function that takes an a and a b and returns a Bool , depending on the outcome you thus fire one of the two guards.因此,这里的p是一个 function,它接受一个a和一个b并返回一个Bool ,这取决于你因此解雇两个警卫之一的结果。 I leave filling in the parts as an exercise.我将填写部分作为练习。

If you want to produce all possible combinations for x and y for which the condition holds, list comprehension is a better tool.如果您想为条件成立的xy生成所有可能的组合,列表理解是一个更好的工具。 You can then work with:然后您可以使用:

combine:: [a] -> [b] -> (a -> b -> Bool) -> [(a, b)]
combine xs ys p = [ … | … <- xs, … <- ys, … ]

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

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