Sunday 5 June 2016

Haskell: Take second elements in list of tuples

Implement a function, which takes list of tuples and return all the second elements of tuples.


Sample.hs
-- Return the second element of a tuple
getSecondEle :: (x, y) -> y
getSecondEle (_, y) = y

-- Return all the second elements from list of tuples
getAllSecondElements :: [(x, y)] -> [y]
getAllSecondElements list = map getSecondEle list

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getAllSecondElements [(1, "Krishna"), (2, "PTR"), (3, "Nayan"), (4, "Raghav")]
["Krishna","PTR","Nayan","Raghav"]
*Main> 
*Main> getAllSecondElements [(1, 2), (2, 3), (3, 5), (4, 7), (5, 11)]
[2,3,5,7,11]
*Main> 



Previous                                                 Next                                                 Home

No comments:

Post a Comment