是的,这是一个单一的任务问题,所以请不要只给我答案,我需要能够了解它是什么以及如何去做(主要是因为还有其他问题,我需要开发一个了解Haskell语言来做到这些!
join :: Eq a => [(a,b)] -> [(a,c)] -> [(a,b,c)].
join需要两个对列表,并返回一个三元组列表。三重奏 仅当存在两个参数列表的成员时才生成 具有相同的第一个元素。列表元素未排序。这个 与关系代数自然连接操作的语义相同。
例如:
join [(2,"S"),(1,"J")] [(2,True),(3,False)])
Should produce the output [(2,"S",True)]
join [(2,"S"),(1,"J")] [(2,1),(2,2),(3,4)])
Should produce the output [(2,"S",1),(2,"S",2)]
我的主要问题是试图弄清楚如何从输入的2个列表创建一个新列表,这些列表具有不同的属性。
join :: Eq a => [(a,b)] -> [(a,c)] -> [(a,b,c)]
join xs [] = xs
join [] ys = ys
join (x:xs) (y:ys) = (x ++ snd(head[x]) ++ snd(head[y]) ++ []) join xs ys
Type error in explicitly typed binding
*** Term : merge
*** Type : [(a,b)] -> [(a,c)] -> [(a,b)]
*** Does not match : [(a,b)] -> [(a,c)] -> [(a,b,c)]
我已尝试了(x ++ snd(head [x])++ snd(head [y])++ [])代码段的几种变体,结果大致相同或模拟错误消息!
答案 0 :(得分:1)
您的类型不匹配
join :: Eq a => [(a,b)] -> [(a,c)] -> [(a,b,c)]
join xs [] = xs
join [] ys = ys
-- ^^^^ three different types involved!
xs
和ys
的类型为[(a, b)]
和[(a, c)]
,因此,它们不能是[(a,b,c)]
的结果类型。
您必须从xs
和ys
创建结果数据,例如
join ? ? = ... (a, b, c) ...
你知道吗?
提示:
的主体是什么makeTuple :: (a, b) -> (a, c) -> (a, b, c)
-- ^ ^
-- : |
-- : +-- only one value exists you can put here
-- :
-- +····· only one value exists you can put here
唯一可能的两个功能是
makeTuple (x1, y) (x2, z) = (x1, y, z)
和
makeTuple (x1, y) (x2, z) = (x2, y, z)
同样,您的join
必须保留结果类型。
来自签名
join :: Eq a => [(a,b)] -> [(a,c)] -> [(a,b,c)]
您知道类型a
是等同的,您知道关于b
和c
类型的无。
一种简单的方法是
join xs ys = [(xa, xb, yc) | (xa, xb) <- xs, (ya, yc) <- ys, xa == ya]
-- ^^^^^^^^
-- from `Eq a` constraint