werd
werd

Reputation: 646

List operations

I have a function cc declared as following (1st parameter is a (list) and 2nd parameter is b (list as well), it should return 3rd list:

cc :: [(String, String)] -> [(String, String)] -> [(String, String)]
cc a b = do

Example:

a = [("aaa", "xxx"), ("bbb", "xxx")]
b = [("xxx", "ccc"), ("xxx", "ddd")]
c should be [("aaa", "ccc"), ("aaa", "ddd"), ("bbb", "ccc"), ("bbb", "ddd")]

c is composition of a and b where each a pairs second "index" is b pairs first "index". So a ("aaa", "xxx") pair's second "index" is "xxx" and its defined as b ("xxx", "ccc") first "index". Regarding to that we create(add) this new pair ("aaa", "ccc") to the return list.

Question is how to do that in Haskell? :)

Best regards!

Upvotes: 0

Views: 284

Answers (3)

Landei
Landei

Reputation: 54584

import Control.Applicative

c = (,) <$> (fst.unzip) a <*> (snd.unzip) b

-- or --

c = liftA2 (,) (fst $ unzip  a) (snd $ unzip b)

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183988

The simplest way to do that is a list comprehension,

cc a b = [(u,x) | (u,v) <- a, (w,x) <- b, v == w]

we pair up all elements of a with all elements of b and filter according to the condition, assembling the result from the parts.

Upvotes: 4

hammar
hammar

Reputation: 139930

Use a list comprehension to grab all the combinations of pairs from both lists, with a condition that the second element of the first pair equals the first element of the second pair:

[(x, z) | (x, y1) <- a, (y2, z) <- b, y1 == y2] 

Upvotes: 3

Related Questions