主要思想是我有两个输入列表,包括元组,列表A(x,y)和列表B(y,z)在输出中我需要编译由元素组成的列表C(x,z) )如果y来自A == y来自B
在函数cc中,列表中的所有输入元组都有递归循环。函数getValue从A中找到与(x,y)对应的所有元组。问题是在getValue中有可能找到多个元组。问题是如何将getValue中的所有元组添加到cc结果列表中。目前我有一个错误
Couldn't match type ‘(String, String)’ with ‘[(String, String)]’
例如[(a,b),(e,b)] [(b,c),(b,d)]应给出结果[(a,c),(a,d),(e ,c),(e,d)]
isInDictionary :: String -> [(String,String)] -> Bool
isInDictionary x [] = False
isInDictionary x((x1,y1):ys) = any (==x) (map fst ys) || x == x1
getValue :: (String,String) -> [(String,String)] -> [(String,String)]
getValue (x,y)[] = []
getValue (x,y)((x1,y1):ys) =
if (y == x1)
then (x,y1) : getValue (x,y) ys
else getValue (x,y) ys
cc :: [(String,String)] -> [(String,String)] -> [(String,String)]
cc [] ((x2,y2):ys) = []
cc ((x1,y1):xs) [] = []
cc [] [] = []
cc ((x1,y1):xs)((x2,y2):ys) =
if( isInDictionary y1 ys )
then (getValue (x1,y1) ys) : cc xs ysa --fix head
else if (y1 == x2)
then ( (x1,y2) : cc xs ysa)
else (cc xs ysa)
where ysa = (ys ++ [(x2,y2)])
答案 0 :(得分:2)
您的代码看起来不必要复杂。你不能这样做吗?
cc :: [(String,String)] -> [(String,String)] -> [(String,String)]
cc as bs = [(x, z) | (x, y1) <- as, (y2, z) <- bs, y1 == y2]
至于(getValue (x1,y1) ys) : cc xs ysa
中的类型错误,可以使用++
(连接列表)而不是:
来修复。