user1189352
user1189352

Reputation: 3875

Haskell - Searching through a list of pairs

I'm trying to make something so that it takes a Book and a string and then returns the value that's associated with the string in the book... so what I have so far is:

data Answer = T | F
    deriving (Eq,  Show, Ord)

type Book = [(String, Answer)] 

testBook :: Book
testBook = [("aT", T), ("bF", F)]

and I want to do it so that let's say i put:

test testBook "aT"

^ the answer will come out to T.

i'm doing something like:

test::Book->String->Answer
test a b = [x | (y, x) <- a, y == b] 

but i know that's completely off.. how can I compare the String to what's in the Book? it seems simple but the syntax for Haskell is really hard to get used to

Upvotes: 0

Views: 1307

Answers (2)

Linus Arver
Linus Arver

Reputation: 1368

Use the "lookup" function (available in Prelude).

Upvotes: 3

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

Your code is on the right track. Right now, you get a list of answers regardless of the value of b. You need to add a condition that checks whether the first item of the tuple is equal to b; to do this, you will have to give it a name rather than using _.

You can add a condition to a list comprehension by using a comma and an expression:

[x | x <- a, x > 10]

will get you all the values from a greater than 10, for example.

I will let you figure out how to put my advice together yourself.

Upvotes: 2

Related Questions