Reputation: 11
I would like to have list of tuples [(a,b,c)..] where a is String, b and c are Num. I will have a function, possibly pattern matching comprehension, that will only search for the first element (Unique ID) in any of the tuples in the list and if a match is found, the function will return remaining two elements in the tuple.
I'm new to programming and after much research I thought I would start with Haskell. I'm finding this http://learnyouahaskell.com very useful to start with but stuck at how comprehension and type annotations plays a role in pattern matching. So far what I see consistent in comprehension syntactically is that
{ Manipulate Set B, but mind the predicate | Trim it down further to make Set B | Select set A, Predicate }
I may sound naive and lazy, but honestly looking for some quick aha breakthrough so I can move on. Thanks in advance.
Upvotes: 1
Views: 713
Reputation: 3548
getMtach [] _ = []
getMtach ((a, b, c):xs) key
| (a == key) = (b, c) : getMtach xs key
| otherwise = getMtach xs key
Main> getMtach [(1, "abc", 12.3), (2, "asg", 4.5), (1, "xyz", 123)] 1
[("abc",12.3),("xyz",123.0)]
*Main>
*Main> getMtach [(1, "abc", 12.3), (2, "asg", 4.5), (1, "xyz", 123)] 2
[("asg",4.5)]
Upvotes: 0
Reputation: 16156
First, here's how you can pattern match inside list comprehensions:
[(b,c) | (a,b,c) <- input]
-- (b,c) constructs your results
-- (a,b,c) is the pattern matching
Then, just add your predicate:
[(b,c) | (a,b,c) <- input, a == id]
And, since these ids are unique, you're only interested in the first match, so just take 1
from the above result.
Personally, I like do
notation better:
do (a,b,c) <- input
guard (a == id)
return (b,c)
Upvotes: 2