Question

So I have a list of tuples:

[(1,2),(2,3),(3,4)]

for example. And I perform a calculation on its elements. The result of this should be joined to this tuple, but I don't know how.

[(1,2,103),(2,3,809),(3,4,2034)]

is the format I'm thinking of.

Was it helpful?

Solution

Assuming you have a calculation function like:

calculate :: Int -> Int -> Int

you can do

calculateAll :: [(Int, Int)] -> [(Int, Int, Int)]
calculateAll = map (\(x, y) -> (x, y, calculate x y))

or more generally:

calculateAllWith :: (a -> b -> c) -> [(a, b)] -> [(a, b, c)]
calculateAllWith f = map (\(x, y) -> (x, y, f x y))

OTHER TIPS

A quite straightforward solution:

import Control.Applicative ((<*>))

mapResultOn3rd :: (a -> b -> c) -> [(a,b)] -> [(a,b,c)]
mapResultOn3rd f = map (uncurry (,,) <*> uncurry f)

For example, in ghci:

>>> mapResultOn3rd (:) [(1,[2]), (3,[4,5])]
[(1,[2],[1,2]),(3,[4,5],[3,4,5])]

Use the map function:

calc :: (Int, Int) -> (Int, Int, Int)
calc = error "Implement me"

calcList :: [(Int, Int)] -> [(Int, Int, Int)]
calcList = map calc

You could also use a list comprehension in GHCi:

Prelude> let list = [(1,2),(2,3),(3,4)]
Prelude> [(x,y,x*y) | (x,y) <- list]
[(1,2,2),(2,3,6),(3,4,12)]

http://www.haskell.org/haskellwiki/List_comprehension

Or use the list as a monad:

Prelude> do (x,y) <- list; return (x,y,x*y)
[(1,2,2),(2,3,6),(3,4,12)]

But I prefer the list comprehension :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top