我刚刚开始学习haskell遇到个题目做不出来,要求写一个function.
它接受一个长度为偶数的 list 和一个条件返回新的list
findBonding :: Eq a => (a -> a -> Bool) -> [a] -> Maybe [(a,a)]
元组 list 满足所有元素都是从原list来的且出现一次 就是俩俩组合,且满足f
findBonding (x -> y -> x y<6) [1, 2, 3, 4] 得到 [(1,2),(3,4)] , [(1,3),(2,4)] [(1,4),(2,3)]
findBonding (x -> y -> x*y<10) [1, 2, 3, 4] 得到 [(1,2),(3,4)] , [(1,3),(2,4)] , [(1,4),(2,3)]
这是我已经写的代码
findBonding :: Eq a => (a -> a -> Bool) -> [a] -> Maybe [(a,a)]
findBonding f xs
|length xs `mod`2/=0 =Nothing
| and [elem (y, x) rel | (x, y) <- rel]
= Just(rel)
| otherwise = Nothing
where
rel = [(a, b) | a <- xs, b <- xs, a /= b, f a b]
只能返回符合条件f的所有可能组合,但是弄不出俩俩组合的样子
代码语言:javascript复制 findBonding (x -> y -> x*y < 21) [2..7]
=> Just [(2,3),(2,4),(2,5),(2,6),(2,7),(3,2),(3,4),(3,5),(3,6),(4,2),(4,3),(4,5),(5,2),(5,3),(5,4),(6,2),(6,3),(7,2)]
这个条件只有一个可能的bond 就是[(2,7),(3,6),(4,5),(5,4),(6,3),(7,2)]
T T 我做了俩天了实在想不出该怎么做