How to get an element inside of a list of tuples? For example
list = [(Tris, 23, 1.40), (Aif, 20 , 1.70)]
I want all the ages
[23,20]
I know that I can use
age = (_,x,_) = x
But it only works with tuples and not a tuple inside a list.
You will need to perform a map
ping where for each item in the list you map it to its age.
You can do this with the map :: (a -> b) -> [a] -> [b]
function , so this will look like:
allAges = map …
where I leave filling in …
as an exercise.
you can solve it recursively like:
allages [] = []
allages ((_,x,_):xs) = x : allages xs
I know that I can use
age (_,x,_) = x
But it only works with tuples and not a tuple inside a list.
Why are you saying this? Surely if you know that
age (_,x,_) = x
then you also know that
ages [(_,x,_)] = [x]
and
ages [(_,x,_), (_,y,_)] = [x,y]
ages [(_,x,_), (_,y,_), (_,z,_)] = [x,y,z]
....
etc. And since we've already established that
ages [ (_,y,_), (_,z,_)] = [ y,z]
ages [ (_,z,_)] = [ z]
so that surely
ages [ ] = [ ]
we can just write down these equations,
ages [ ] = [ ]
ages ([(_,x,_)] ++ moreTuples) = ages [(_,x,_)] ++ ages moreTuples
and since we know that ages [(_,x,_)] = [x]
, it's
ages [ ] = [ ]
ages ([(_,x,_)] ++ moreTuples) = [ x ] ++ ages moreTuples
so now all that's left to make it valid Haskell syntax is to rewrite the first equation's argument using the :
operator, along the lines of
[ a ] ++ moreTuples ==
a : moreTuples
and you're done.
So in the end you did know how to do this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.