Meeran
Meeran

Reputation: 91

Comparing indexes of a list of tuples to a list of integers

I am very new to functional programming and haskell.

Basically, I have formed a list of tuples where they are ordered and indexed, like so

listOfCharTuples = [(1,H),(2,a),(3,s),(4,k),(5,e),(6,l),(7,l)

and as an input I will be given a list of ordered integers that will be at maximum, the number of tuples in this list.

I want a way to make a function that prints out the respective characters given the input of the list of integers, so if the list given was, for example [1,3,5], I would want the function to print "Hse".

I may be given any list of input characters, the only progress I've made so far is to make them into a list of indexed tuples, and I am really struggling to solve this

Upvotes: 0

Views: 73

Answers (2)

YS-L
YS-L

Reputation: 14738

As hinted in the comment, a possible solution that is more general (does not require orderedness of the input) can make use of the lookup function:

import Data.Maybe (fromMaybe)

lookupAll :: [(Int,Char)] -> [Int] -> String
lookupAll tuples = map (\x -> fromMaybe '?' $ lookup x tuples)

Examples:

putStrLn $ lookupAll listOfCharTuples [1,3,5] -- Hse
putStrLn $ lookupAll listOfCharTuples [5,3,1] -- esH

Upvotes: 0

aghitza
aghitza

Reputation: 176

Here is a possible definition, using a list comprehension:

f :: [Int] -> [(Int,Char)] -> String
f is ts = [c | (i,c) <- ts, i `elem` is]

and then

f [1,3,5] listOfCharTuples

Upvotes: 1

Related Questions