Monday, March 10, 2008

Another cute Haskell function

join :: Eq a => [(a,b)] -> [(a,c)] -> [(a,(b,c))]
join a1 a2 = [ (a,(b,c)) | (a,b) <- a1, c <- [ c | (a',c) <- a2, a == a' ] ]

infixr 5 ⋈
(⋈) :: Eq a => [(a,b)] -> [(a,c)] -> [(a,(b,c))]
(⋈) = join

-- for example:
[("a",1),("b",2),("c",3)] ⋈ [("a",'a'),("b",'b'),("c",'c')]

2 comments:

Paul Steckler said...

The a == a' bit means this is a
natural join, i.e. using an
equality predicate. Why not
make the join parameteric in the
test predicate?

Surely you've nothing better to do.

-- Paul

Stella said...

Hi,

I understand the function u wrote but I am having trouble to create function using data type Maybe.

join :: Eq => [(a,b)] -> [(a,c)] -> [(a,b,Maybe c)]

Can you help? Thanks.