yousuke07
yousuke07

Reputation: 5

How to return value without Maybe after use lookup to get the value from the table?

I am trying to return a string and combine it with another. A table has been made with the following code.

type Table = [(Char, String)]

and the Table look like this.

t = [(A, "Apple"),(B, "Boy"),(C, "Car"),(D, "Day")...]

I would like to combine the string and return it. For example

(lookup 'A' t) ++ (lookup 'B' t) = "AppleBoy"

But its not be able to do that because a maybe value has been returned after lookup function. Please help me to understand how to do that.

Upvotes: 0

Views: 170

Answers (1)

Aplet123
Aplet123

Reputation: 35560

You can lift the ++ function to the Applicative level with liftA2:

import Control.Applicative
liftA2 (++) (lookup 'A' t) (lookup 'B' t)
-- Just "AppleBoy"

Alternatively, this can be written as:

(++) <$> (lookup 'A' t) <*> (lookup 'B' t)

See this excellent chapter from Learn you a Haskell for more information.

Upvotes: 4

Related Questions