Jump to content

Haskell pattern matching [(a,b,c)] to [a]?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
Guenhwyvar

Guenhwyvar

    Newbie

  • Members
  • Pip
  • 3 posts
Hiya, I am new to haskell and I need to use pattern matching to extract the list a from a tuple list. I have tried

where [(a,_,_)] = a

But is says the type if then a, not [a]? How to I extract the full list of a's?

Thanks

#2
Sysop_fb

Sysop_fb

    Programmer

  • Members
  • PipPipPipPip
  • 160 posts
  • Location:Missouri
Sorry didn't see your question.

What you said seems a bit vague to me.
If you have a list with a single triple element tuple in it then all you need to do is pull out the tuple and then do your pattern matching

tst = [(1,2,3)]
fst' (a, _, _) = a

ghci> fst' (head tst)
1

If you have a list of multiple tuples then you'd have to iterate through the list
tst = [(1,2,3),(4,5,6),(7,8,9)]
fst' (a, _, _) = a

ghci> [fst' x | x <- tst]
[1,4,7]

Edit:
Oh you could also do pattern matching in list comprehension
let tst = [(1,2,3), (1,2,3), (4,5,1), (5,6,6)]

ghci> [a | (a, b, c) <- tst]
[1,1,4,5]

Edited by Sysop_fb, 21 December 2011 - 05:39 PM.

"The best optimizer is between your ears" - Michael Abrash
Saying you can optimize a program is like saying you understand how a program works on every level of every facet on a specific machines configuration.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users