123Ex
123Ex

Reputation: 277

get value from list tuple in haskell

These are my haskell lists

lst1 = ["a,","b","c"]  
lst2 = [("a","123"),("b","345")]

I want to get a element from "lst1" and compare with "lst2" and if the value is exist want to replace with the second value in tuple replace the 2nd value.

so it's like this lst1 had "a" and "b" so output should be ["123","345","c"] so how can I do this in haskell? pls help me Can i do it in any other way?? thankxx!

Upvotes: 1

Views: 2544

Answers (2)

Landei
Landei

Reputation: 54574

map (\x -> maybe x snd $ find ((x ==).fst) lst2) lst1

For longer lists you should consider using a Map instead of lst2

[Edit]

import Data.Maybe
subst lst1 lst2 = map (\x -> fromMaybe x $ lookup x lst2) lst1

(Thanks to Chuck)

And just for some pointless fun:

import Data.Maybe
main = print $ subst [("a","123"),("b","345")] ["a","b","c"] 
subst = map.app fromMaybe lookup   
        where app f g x y = f y $ g y x 

The perfect example for easy to write and really hard to understand (at least for me) Haskell code, so I would definitely use one of the other definitions.

Upvotes: 2

David V.
David V.

Reputation: 5708

This is how I'd do it.

import qualified Data.Map as M
import Data.Maybe

lst1 = ["a","b","c"]
lst2 = [("a","123"),("b","345")]

-- For each value of lst1, you want to replace it by something, so you'll be using map '
res = map comb lst1

-- For performance, we convert the 2nd list to a map
m = M.fromList lst2

-- For a value of lst1, you want to find it in the map, 
-- and return the result if found, 
-- or keep the original if not found
comb v = fromMaybe v (M.lookup v m)

Prelude> :r

[1 of 1] Compiling Main ( t.hs, interpreted )

Ok, modules loaded: Main.

*Main> res

Loading package array-0.3.0.1 ... linking ... done.

Loading package containers-0.3.0.0 ... linking ... done.

["123","345","c"]

*Main>

Upvotes: 2

Related Questions