我想多次使用Eq, 这样第一个连音符的第二个元素来自另一个类型而不是其余的
错了,但是,这就是我想要的想法
例如。 [(a,a)] - > [(a,a)] - > Bool ----> [(a,b)] - > [(a,a)] - > 布尔
代码
canColor :: Eq a => [(a, a)] -> [(a, a)] -> Bool
canColor _ [] = True
canColor xs ((x,y):rest) =
if findNeighbour xs x == findNeighbour xs y
then False
else canColor xs rest
findNeighbour :: Eq a => [(a, a)] -> a -> Maybe a
findNeighbour [] _ = Nothing
findNeighbour ((x,y):rest) z =
if x == z
then Just y
else findNeighbour rest z
输入数据和期望值
Main> canColor [('a',"purple"),('b',"green"),('c',"blue")] [('a','b'),('b','c'),('c','a')]
True
Main> canColor [('a',"purple"),('b',"green"),('c',"purple")] [('a','b'),('b','c'),('c','a')]
False
Main> canColor [('1',"purple"),('2',"green"),('3',"blue")] [('1','2'),('2','3'),('3','1')]
True
**Main> canColor [('a', 4),('b',5),('c', 6 )] [('a','b'),('b','c'),('c','a')]
True
Main> colors [('a', 4),('b', 4 ),('c', 5 )] [('a','b'),('b','c'),('c','a')]
False**
答案 0 :(得分:9)
只需为它们提供不同的类型变量,并且两者都需要Eq
。我想你正在寻找这个代码:
canColor :: (Eq a, Eq b) => [(a, b)] -> [(a, a)] -> Bool canColor _ [] = True canColor xs ((x,y):rest) = if findNeighbour xs x == findNeighbour xs y then False else canColor xs rest findNeighbour :: Eq a => [(a, b)] -> a -> Maybe b findNeighbour [] _ = Nothing findNeighbour ((x,y):rest) z = if x == z then Just y else findNeighbour rest z
或者这个更简洁和惯用的代码:
canColor :: (Eq a, Eq b) => [(a, b)] -> [(a, a)] -> Bool canColor xs = all (\(x,y) -> lookup x xs /= lookup y xs)