travis
travis

Reputation: 45

extracting a tuple out of a list of tuples using haskell

I have this derived data type AcInfo which consists of the following user created data types [(AcNo, Name, City, Amnt)] (all are strings except Amnt which is an Int) what i want is to get a tuple out of the following list by checking the AcNo.

I made the declaration and a bit further, but I am finding it hard to figure out what to do next. The declaration:

accountDetails :: AcInfo -> AcNo -> [Name, City, Amnt]
accountDetails dbase number 

Will the use of list comprehension be useful? Furthermore, what would be a good way of going for a solution?

Thanks in advance.

Upvotes: 2

Views: 1177

Answers (2)

Daniel Lyons
Daniel Lyons

Reputation: 22803

You could do this with list comprehensions pretty easily:

locateAcct :: AcNo -> [(AcNo, Name, City, Amnt)] -> (AcNo, Name, City, Amnt)
locateAcct account db = head [ tup | tup@(ac, _, _, _) <- db, ac == account ]

Of course, by using head, we open ourselves up to the possibility of a failed match. Perhaps a better approach would be to use something like the safe library's version of headMay, which returns Nothing if the list is empty:

locateAcct :: AcNo -> [(AcNo, Name, City, Amnt)] -> Maybe (AcNo, Name, City, Amnt)
locateAcct account db = headMay [ tup | tup@(ac, _, _, _) <- db, ac == account ]

Now if that account doesn't exist, you get Nothing instead of a pattern match failure.

Upvotes: 3

misterbee
misterbee

Reputation: 5172

find ((==) target . fst4) : http://zvon.org/other/haskell/Outputlist/find_f.html

where fst4 is a version of fst that takes a 4-tuple. Not sure if it is in a library, but it is easy to write.

Upvotes: 1

Related Questions