haskell 求助
- 2019 年 12 月 2 日
- 筆記
我剛剛開始學習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的所有可能組合,但是弄不出倆倆組合的樣子
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 我做了倆天了實在想不出該怎麼做